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!

有帮助吗?

解决方案

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

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top