Java-12.3 instanceof, isInstance, and isAssignableFrom
This section describes three methods for detecting object types: instanceof, isInstance, and isAssignableFrom.
Example:
package com.ray.ch12;public class Test {public static void main(String[] args) {try {Class
AClass1 = (Class
) Class.forName(com.ray.ch12.Sub);System.out.println(AClass1.newInstance() instanceof Sub);System.out.println(AClass1.newInstance() instanceof Father);System.out.println(AClass1.isInstance(new Sub()));System.out.println(AClass1.isInstance(new Father()));System.out.println(AClass1.isAssignableFrom(Sub.class));System.out.println(AClass1.isAssignableFrom(Father.class));} catch (ClassNotFoundException e) {e.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}class Father {}class Sub extends Father {}
Output:
True
True
True
False
True
False
1. Note the following when reading the above Code:
(1) The instanceof parameter is a class
(2) parameters following isInstance are class objects.
(3) The parameter following isAssignableFrom is the Class Object of the Class.
These three methods are used to detect object types.
2. Note the following points from the output result:
(1) instanceof supports upward transformation, so the above AClass1 is also Father Class type
(2) isInstance and isAssignableFrom do not support upward transformation. Therefore, the output of AClass1 can only point to Sub, but cannot recognize Father.
Summary: This chapter mainly describes the methods instanceof, isInstance, and isAssignableFrom for the three object types, as well as the corresponding notes.