3

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";
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
jrpalla
  • 159
  • 2
  • 10

3 Answers3

6

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());
Lone nebula
  • 4,768
  • 2
  • 16
  • 16
3
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>>.

nakosspy
  • 3,904
  • 1
  • 26
  • 31
0

Since all instances of a generic class share the same class object, the type parameter doesn't matter to the runtime, so you can simply do:

Class.forName("A").newInstance();

and cast the result to whatever type you need.

meriton
  • 68,356
  • 14
  • 108
  • 175