Reputation: 63442
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
.
Upvotes: 5
Views: 922
Reputation: 234795
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.
Upvotes: 4
Reputation: 117587
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);
Upvotes: 3
Reputation: 1788
You can't do it directly, but you can add an interface that T implements to create an instance, or an array of T.
Upvotes: 0