why instanceof does not work with Generic? [duplicate]

允我心安 提交于 2019-11-30 11:22:14
Jim Garrison

You cannot do it this way. Fortunately, you already have a Class<T> argument so instead do

myClass.isAssignableFrom(obj.getClass())

This will return true if obj is of class myClass or subclass.

As @ILMTitan pointed out (thanks), you will need to check for obj == null to avoid a potential NullPointerException, or use myClass.isInstance(obj) instead. Either does what you need.

Short answer: because a type parameter in Java is something just used by the compiler to grant type safety.

At runtime, type information about generic types is discarded because of type erasure but instanceof is a runtime check that needs a concrete type (not a type variable) to work.

T is a parameterized type and exists for compilation purposes. It does not exist at runtime because of type erasure.

Therefore, obj instanceof T is not legal.

Because java uses erasure, generic types can not be used to check against.

To get the desired result, use Class.isInstance().

Generic types will be erased after compilation (generics are for compile time type safety) and will be replaced with most applicable type after compilation.

If you want make this compile, replace T with concrete type, example

obj instance String
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!