I'm trying to implement a class that can initialize values into an object of any class. The initialization of simple structures is already functional, but I got stuck trying to initialize the array of Lists (List<String>[]
).
Is there any way to find out the ParameterizedType
and not just the Class
of the array by getComponentType()
?
Creation of array:
if (cls.isArray()) {
Class<?> c = cls.getComponentType();
if (!c.isPrimitive()) {
Array array = new Array(c, this.sizeArrays);
for (int i = 0; i < this.sizeArrays; i++) {
array.set(i, init(c, c, this.sizeArrays, this.sizeCollection, this.recursionCount, this.values, this.ignoredClass));
}
return array.getArray();
}
Class Array:
class Array<E> {
private final E[] objArray;
public final int length;
public Array(
Class<E> dataType,
int length
) {
//noinspection unchecked
this.objArray = (E[]) java.lang.reflect.Array.newInstance(dataType, length);
this.length = length;
}
void set(
int i,
E e
) {
objArray[i] = e;
}
E[] getArray() {
return objArray;
}
}
Creating List:
if (Collection.class.isAssignableFrom(cls)) {
ParameterizedType t = ((ParameterizedType) cls.getGenericSuperclass());
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
Collection collection;
if (List.class.isAssignableFrom(cls)) {
collection = new ArrayList(this.sizeCollection);
} else if (Set.class.isAssignableFrom(cls)) {
collection = new HashSet(this.sizeCollection);
} else if (Queue.class.isAssignableFrom(cls)) {
collection = new LinkedList();
} else {
collection = new ArrayList(this.sizeCollection);
}
for (int i = 0; i < this.sizeCollection; i++) {
collection.add(init((Class<?>) pt.getActualTypeArguments()[0], pt.getActualTypeArguments()[0], this.sizeArrays, this.sizeCollection, this.recursionCount, this.values, this.ignoredClass));
}
return collection;
}
}
Aucun commentaire:
Enregistrer un commentaire