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.
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.
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