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.
You have two main choices.
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
}
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With