Reputation: 2327
I have a method to build the array for the required type. It works for the primitive types. But when I have array of custom objects it doesn't work. So I have tweaked it. But still it fails. Code is like this :
private Object buildArray( String type, Object object) {
final Class<?> requiredType = loadClass(type);
final String typeName = type.substring(2).replace(";", "").trim();
Object[] array = ((Object[]) object);
ArrayList<Object> arrayList = new ArrayList<Object>(array.length);
for (Object customObj : array) {
arrayList.add(castToRequiredType(typeName, customObj));
}
return arrayList.toArray();
}
In this castToRequiredType
: casts the CustomObject
to the CustomType
where CustomType
is a class. And array to be build is of type CustomType
. I am stuck at dynamically building the array of CustomType
.
Any help in this direction is welcome. Thanks in advance.
Upvotes: 1
Views: 4120
Reputation: 76828
If you have an array of Object
, you can use Arrays.copyOf
to convert it to a different type:
CustomType[] ca = Arrays
.copyOf(array, array.length, CustomType[].class);
Upvotes: 2