3

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!

2 Answers2

3

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

Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
  • 1
    Clever solution but you know may be the list is empty! – Mohammad Ali Bozorgzadeh Feb 05 '14 at 12:48
  • It should go without saying that a size check should be done first. But I've added that to the answer. – Martin Dinov Feb 05 '14 at 12:50
  • 1
    Of course you could still do it with reflection. See http://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime/3404169#3404169 and http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/ParameterizedType.html#getActualTypeArguments%28%29. But keep in mind that doing this is probably a sign of (very) bad design. – Joeri Hendrickx Feb 05 '14 at 13:00
1

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

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105