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 classTest. You can’t prevent type erasure.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.