简体   繁体   English

使用Class.forName实例化参数化类型

[英]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: 如何使用Class.forName实例化A类,因为我有两个字符串变量:

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: 例如,下面的代码将输出没有泛型的class java.util.ArrayList

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>> . 类型A的类型参数在运行时期间不存在,因此您可以将aClassClass<A<B>> aClass Class<A<B>>

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: 由于泛型类的所有实例共享同一个类对象,因此type参数对运行时无关紧要,因此您只需执行以下操作:

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

and cast the result to whatever type you need. 并将结果转换为您需要的任何类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM