简体   繁体   English

如何使用参数创建泛型类型的实例

[英]How to create instance of generic type with parameter

I have following 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();
    }
}

I want to create an instance of generic type T with the parameter of the constructor. 我想用构造函数的参数创建泛型类型T的实例。

I tried to TypeToken , Class<T> , newInstance and etc., but nothing to success. 我尝试过TypeTokenClass<T>newInstance等,但没有成功。 I want some help. 我想要一些帮助。 Thank you for your answer. 谢谢您的回答。

You have two main choices. 你有两个主要的选择。

Reflection 反射

This way is not statically type safe. 这种方式不是静态类型安全的。 That is, the compiler gives you no protection against using types that don't have the necessary constructor. 也就是说,编译器无法保护您不使用没有必要构造函数的类型。

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

You have to declare or import a Factory< T > interface. 您必须声明或导入Factory< T >接口。 There is also an extra burden on the caller to supply an instance thereof to the constructor of SomeClass which further erodes the utility of your class. 调用者还有一个额外的负担,即将其实例提供给SomeClass的构造函数,这进一步侵蚀了类的实用程序。 However, it's statically type safe. 但是,它是静态类型安全的。

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

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

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