I have the following classes:
public class B {
}
public class A<B> {
}
How do I instantiate class A using Class.forName, given that I have two string variables:
String classNameA = "A";
String classNameB = "B";
Due to type erasure, there won't be any generic classes at run time.
For instance, the following piece of code will output class java.util.ArrayList without generics:
List<String> list = new ArrayList<String>();
System.out.println(list.getClass());
Class<B> bClass = (Class<B>) Class.forName(classNameB);
B b = bClass.newInstance();
Class<A<B>> aClass = (Class<A<B>>) Class.forName(classNameA);
A<B> a = aClass.newInstance();
The type parameter of type A does not exist during runtime, so you can cast aClass to Class<A<B>>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With