[英]Java generics for class and new instance
在Java中,如果有:
public class Foo<T> {
public Foo() { }
}
我可以做Foo<Integer> foo = new Foo<Integer>();
但是我找不到使用class
字段的等效语法,这意味着像Foo<Integer> foo = Foo<Integer>.class.newInstance();
之class
东西Foo<Integer> foo = Foo<Integer>.class.newInstance();
不起作用。 有没有办法通过newInstance方法使用泛型?
您只能在没有参数化类型的情况下执行此操作。 Class.newInstance()
不太Class.newInstance()
推荐。 你可以这样做:
//Class<Foo<Integer>> clazz = Foo<Integer>.class; <-- Error
Class<Foo> clazz = Foo.class; // <-- Ok
Foo instance = clazz.getConstructor().newInstance();
希望能帮助到你。
.newInstance()
(以及所有使用Class
东西)是一个反射API,从根本上在运行时起作用。 因此,它与在编译时运行的泛型无关。
newInstance()
是Java早期的API-当时没有泛型。 您必须转换返回值。
同样:将来没有这样做的方法, newInstance()
用于在运行时动态创建对象。 由于Java中的类型擦除,因此在运行时不再有通用信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.