jrpalla
jrpalla

Reputation: 159

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";

Upvotes: 3

Views: 5254

Answers (3)

meriton
meriton

Reputation: 70564

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.

Upvotes: 0

nakosspy
nakosspy

Reputation: 3942

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

Upvotes: 3

Lone nebula
Lone nebula

Reputation: 4878

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());

Upvotes: 6

Related Questions