instanceof on Class objects

If you need to access the metadata of a class or be a bit less type safe than Java is by itself, you will have to get involved with the Java Reflection API.  At that the question may arise, how to check whether one class object is the super class of another. If you are working with objects, you may use the java keyword instanceof. But this won’t work as expected for class objects, since all class objects are instances of Class<?> . So Class<?> owns the method cls1.isAssignableFrom(cls2), checking whether cls1 is a super class/interface or the same as cls2. So it works just like instanceof on objects, but the order of the parameters is switched.

Leave a Reply

Your email address will not be published. Required fields are marked *