Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using class object as generic type

I'm not entirely sure of how to ask this question, which is also why I'm not sure about the title and so on. Here goes.

Say you have a object Foo foo = new Foo(). Is it possible to write code like new ArrayList<foo.getClass()>(), which would on runtime be equivalent to new ArrayList<Foo>()?

Another, but related question is: Suppose that the class Foo extends Exception. Is it then possible to write something like

try{
    // ...
} catch(foo.getClass() e) {
    //
}

which would translate into

try{
    // ...
} catch(Foo e) {
    //
}

?

Whether this would be horrible to do, is not the important part. However, I would like to hear qualified opinions anyway.

like image 595
torbonde Avatar asked Mar 22 '23 00:03

torbonde


1 Answers

No, this is not possible in the Java language specification. Generic parameters are purely a compile-time type-safety mechanism, so defining them at runtime is non-sensical.

Class literals in the code are not interchangeable with Class<T> objects, due to their inherently different roles. The latter only has meaning at runtime, and can vary dynamically.

like image 120
torquestomp Avatar answered Mar 27 '23 23:03

torquestomp