Question

How can i determine if an object is instance of a parametrized type of a generic class for example ArrayList<String>? I tried:

if(obj instanceof ArrayList<String>)

but it failed with compiler error!

Était-ce utile?

La solution

In short, you can't/shouldn't do this, due to type erasure. Parametrized types exist as such only up to compilation and not during runtime. So you can't have type safety ensured by generics and parametrized types at runtime. They are there to ensure type safety while programming, but all such type information is gone by the time the program is running, as types are substituted as appropriate and what you are left with are non-parametrized normal classes. At best, you can do something like this:

obj instanceof ArrayList

to check whether obj is an instance of ArrayList and:

obj.get(0) instanceof String

to check whether the stored objects in the ArrayList are instances of String. Of course, you might want to check whether there are any elements first.

Alternatively, you could use reflection (see for example getActualTypeArguments() from the ParametrizedType interface).

Autres conseils

Because There won't be any Generics at run time in java. So Compiler won't allow this logic.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top