Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

I tried to TypeToken, Class<T>, newInstance and etc., but nothing to success. I want some help. Thank you for your answer.

like image 219
Taehoon Kim Avatar asked Mar 17 '23 01:03

Taehoon Kim


1 Answers

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. 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. 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
    }
}
like image 155
Judge Mental Avatar answered Apr 16 '23 12:04

Judge Mental