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

Tae*_*Kim 4 java generics types instance

我有下课.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我想用构造函数的参数创建泛型类型T的实例.

我想TypeToken,Class<T>,newInstance和等,但没有成功.我想要一些帮助.谢谢您的回答.

Jud*_*tal 6

你有两个主要的选择.

反射

这种方式不是静态类型安全的.也就是说,编译器无法保护您不使用没有必要构造函数的类型.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

您必须声明或导入Factory< T >接口.调用者还有一个额外的负担,即将其实例提供给构造函数,SomeClass这会进一步削弱您的类的实用程序.但是,它是静态类型安全的.

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
    }
}
Run Code Online (Sandbox Code Playgroud)