I need to create an array of generics at runtime and, because of java type erasure, I am using super type tokens to achieve that. I created the following abstract class:
public abstract class TypeReference<T> {
private final Type type;
public TypeReference() {
Type superclass = getClass().getGenericSuperclass();
type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
}
public Type getType() {
return type;
}
}
and I'm trying to generate my array with the following code:
public static void main(String[] args) {
TypeReference<LinkedListNode<Integer>> token = new TypeReference<>() {};
LinkedListNode<Integer>[] array = generateRandomArray(10, token);
}
public static <T> T[] generateRandomArray(int size, TypeReference<T> c) {
return (T[]) Array.newInstance(c.getType().getClass(), size);
}
This solution doesn't work because c.getType().getClass()
is returning ParameterizedType
. I should pass c.getType()
(which is LinkedListNode<Integer>
), but this last solution doesn't compile since Type
cannot be cast to Class<?>
.
Do you know how can I leverage the Super Type Token to generate the array?
Thank you.