Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate parameterized type using Class.forName

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";
like image 679
jrpalla Avatar asked Jul 11 '26 06:07

jrpalla


2 Answers

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());
like image 50
Lone nebula Avatar answered Jul 15 '26 10:07

Lone nebula


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>>.

like image 22
nakosspy Avatar answered Jul 15 '26 08:07

nakosspy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!