4

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.

1
  • You can't create a new instance of a generic. Potentially instead you could create a factory that does that for you (so long as it's a type of CustomView, your class wouldn't care). Commented Feb 11, 2015 at 17:11

1 Answer 1

7

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer! This is working well, but I want use only type <T> in SomeClass<T>. isn't there way to unuse parameter Class<T> of constuctor? that is, how to make Class<T> instance of type <T>.
If you can pass in an actual instance of T, you can use either approach I mention. The first works if you replace clsT with t.getClass(); the second works if you make sure CustomView is self-bounded and has a make() method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.