Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use reflection to create a generic parameterized class in Java

How can I use reflection to create a generic parameterized class in Java?

I have

public class SomeClass<T> {
   public SomeClass<T>() {
   }
}

and I need an instance of it.

I've tried variations of

Class c = Class.forName("SomeClass");

but could not find a syntax that would allow me to get an appropriately typed instance, like, say

SomeType instance = (SomeType)Class.forName("SomeClass<SomeType>").createInstance();

So, how could I go about doing this?

like image 816
luvieere Avatar asked Jun 16 '11 14:06

luvieere


3 Answers

Java uses erasure-based generics (i.e., the type parameters are erased at runtime—for example, List<Integer> and List<String> are treated as the same type at runtime). Since reflection is inherently a runtime feature, the type parameters are not used or involved at all.

In other words, you can only instantiate the raw type (SomeClass, not SomeClass<T>) when you're using reflection. You will then have to manually cast the type to the generic version (and generate an unchecked warning).

like image 144
Chris Jester-Young Avatar answered Sep 28 '22 00:09

Chris Jester-Young


See/search for "Type erasure". Generics are for compile time and they are not availble at runtime so what you are trying is not possible. You need to use the raw type for reflection

like image 31
fmucar Avatar answered Sep 28 '22 01:09

fmucar


Because of type erasure, at runtime SomeClass is all there is left of SomeClass<SomeType>.

like image 32
Waldheinz Avatar answered Sep 28 '22 00:09

Waldheinz