문제

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