If I have something like:
class Test<T extends X> {
public T test() {
T t = /* ... */;
return t;
}
}
How can I capture T
's class so I can instantiate it? Are there workarounds to prevent type erasure? I don't even need to have access to T
's methods, X
's will do just fine, but I need to return a T
.
The only thing you can do is to pass the class of T as an extra argument, either to test()
or set a member field in class Test
. You can't prevent type erasure.
class Test<T extends X> {
private Class<T> mClass;
public Test(Class<T> c) {
mClass = c;
}
public T test() {
T t = mClass.newInstance();
return t;
}
}
Or you can pass a factory object to the same effect. This works well when you need to use something other than a default constructor.
Define it as:
class Test<T extends X>
{
public T test(Class<T> c)
{
T t = c.newInstance();
return t;
}
}
and use it like:
Test<Foo> t = new Test<Foo>();
t.test(Foo.class);
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