我有以下类(class)。
public class SomeClass<T extends CustomView> {
public void someMethod() {
T t; // = new T(context) ...compile error!
// I want instance of SomeType that have parameter(context) of constructor.
t.go();
}
}
我想用构造函数的参数创建泛型类型 T 的实例。
我试过 TypeToken
, Class<T>
, newInstance
等等,但没有成功。我需要一些帮助。谢谢你的回答。
最佳答案
您有两个主要选择。
反射(reflection)
这种方式不是静态类型安全的。也就是说,编译器无法防止您使用没有必要构造函数的类型。
public class SomeClass< T > {
private final Class< T > clsT;
public SomeClass( Class< T > clsT ) {
this.clsT = clsT;
}
public someMethod() {
T t;
try {
t = clsT.getConstructor( context.getClass() ).newInstance( context );
} catch ( ReflectiveOperationException roe ) {
// stuff that would be better handled at compile time
}
// use t
}
}
工厂
您必须声明或导入 Factory< T >
界面。调用者还需要为 SomeClass
的构造函数提供其实例的额外负担。这进一步削弱了你类(class)的效用。但是,它是静态类型安全的。
public class SomeClass< T > {
private final Factory< T > fctT;
public SomeClass( Factory< T > fctT ) {
this.fctT = fctT;
}
public someMethod() {
T t = fctT.make( context );
// use t
}
}
关于java - 如何创建带参数的泛型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28458408/