Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture generic type in Java

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.

like image 509
rid Avatar asked Oct 07 '12 05:10

rid


2 Answers

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.

like image 152
Ted Hopp Avatar answered Sep 25 '22 14:09

Ted Hopp


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);
like image 32
Eng.Fouad Avatar answered Sep 21 '22 14:09

Eng.Fouad