问题
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.
回答1:
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.
回答2:
There is a subtle, but existent difference between a type and its Class literal.
The class literal is an object that models a type. Among other things, it provides details about the type's implementation.
When you reference an object you use a type. The same holds for generic parameters. They are represented, on the source code, with a type.
For example, while writing
String foo = "foo";
is legal
"".getClass() foo = "foo"
is not.
I hope this makes sense.
Edit: A usual pattern, when working with Generics, is to pass the Class as an argument.
<T> doSomething(Class<T> clazz);
Edit2: edited according to @millimoose comments
回答3:
Java doesn't support that syntax, but if your goal is to create a Collection whose type is determined by the type of an instance, create a typed method, eg:
public static <T> List<T> createList(T object) {
List<T> list = new ArrayList<T>();
list.add(object);
return list;
}
Whatever type you pass in will determine the type of the List returned. It's not a runtime determination - it's a compile time check, but it's the closest thing to how I interpret your intention.
来源:https://stackoverflow.com/questions/19420617/using-class-object-as-generic-type