Using a class object as a generic type

I am not quite sure how to ask this question, and that is why I am not sure about the title and so on. Here it goes.

Say you have an object Foo foo = new Foo(). Is it possible to write code of a type new ArrayList<foo.getClass()>()that will be equivalent at runtime new ArrayList<Foo>()?

Another, but related question: suppose a class Fooextends Exception. Is it possible then to write something like

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

which translates to

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

?

Was it a terrible but not important part. Nevertheless, I would like to hear qualified opinions.

+4
source share
3 answers

, Java. , .

Class<T> - - . .

+6

, .

- , . , .

, . . .

,

String foo = "foo";

"".getClass() foo = "foo"

.

, .

: Generics .

<T> doSomething(Class<T> clazz);

Edit2: @millimoose

0

Java does not support this syntax, but if your goal is to create a collection whose type is determined by the type of the instance, create a typed method, for example:

public static <T> List<T> createList(T object) {
    List<T> list = new ArrayList<T>();
    list.add(object);
    return list;
}

No matter what type you pass, the type of the returned list will be determined. This is not a run-time definition - it is a compile-time check, but it is closest to how I interpret your intent.

0
source

All Articles