1

I'm doing a mapping using reflection.

With reflection I can know if each of the the Fields of a Class refers to an attribute of type "array", and also I can get the Class with the type of the array.

Now, I want to set the value of the field of an object. Now, for some reason, I can get the data to fill the object field, but it's not in the form of an array. Is, instead, a Collection<?>.

Just to make it easy to visualize, I have some code like that:

/** create a new T instance, with the data taken from something*/
<T> T convert(Class<T> cls, Object something) {
    T obj = cls.newInstance();
    for (Field field : cls.getFields()) {
        if (field.getType().isArray()) {
            Class<?> arrayType = field.getType().getComponentType();
            Collection<?> collection = this.getData(arrayType, something);

            Object array = CONVERT(collection);

            field.set(obj, arrayData);
        }
    }
}

At the end of the day, I need to convert a Collection<?> object to (hypotetically) a ?[] object, where "?" is dinamically correct.

I know there is collData.toArray(), but it builds an Object[], witch is incompatible; and I know there is collData.toArray(T[]), but I have no idea of how to use it in this context.

3 Answers 3

2

As you already have a component type, use Array.newInstance:

Object[] array = collection.toArray(
                    (Object[])Array.newInstance(arrayType, collection.size()));
field.set(obj, array);
Sign up to request clarification or add additional context in comments.

2 Comments

Object array = collection.toArray(Array.newInst...); as the type is not an Object array.
@JoopEggen, whatever. Any non-primitive array can be upcasted to Object[]. For this code it does not matter.
1

Or do it the following way, which is easier to understand. Create an array and provide it as parameter to colleation.toArray :

Object[] array = collection.toArray(new Object[collection.size()] );
field.set(obj, array);

Comments

0

Collection as a toArray() function that return an array of what the Collection is filled. From the java doc :

String[] y = x.toArray(new String[0]);

1 Comment

Yes, and if you're not a fool, you can change it as you want... Object[] y = x.toArray(new Object[0]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.