A sentence summary:
- The IsAssignableFrom () method is judged from the perspective of class inheritance , and theinstanceof () method is judged from the perspective of instance inheritance .
- The IsAssignableFrom () method is to determine whether a class is a parent class, and theinstanceof () method is to determine whether a class is a subclass.
1. Class.isassignablefrom () method
Class.isassignablefrom () is used to determine whether a class Class1 is the same as another class Class2 or a subclass or interface of another class.
The format is:
Class1.isassignablefrom (CLASS2)
Both the caller and the parameter are java.lang.Class types.
2.class.instanceof () method
class.instanceof () is an instance of a class or interface that is used to determine whether an object instance is a subclass or a child of its subclasses.
The format is:
obj instanceof TypeName
The first parameter is the object instance name, and the second argument is a specific class name or interface name, such as String,inputstream. Its return value is Boolean.
3. Specific usage
Turn from (http://sunnylocus.iteye.com/blog/555676)
Package Com.bill99.pattern;public class Assignabletest {public assignabletest (String name) {}/** * determines a Whether a class is the parent of another class * is print true * No print false */public static void TestIsAssignedFrom1 () {System.out.println (" String is the parent of Object: "+string.class.isassignablefrom (Object.class)); }/** * Determines if a class is the parent of another class * is print true * No print false */public static void TestIsAssignedFrom2 () {Sy Stem.out.println ("Object is the parent of String:" +object.class.isassignablefrom (String.class)); }/** * Determines if a class is the same as another class * is print true * No print false */public static void TestIsAssignedFrom3 () {Sys Tem.out.println ("Object and object are the same:" +object.class.isassignablefrom (Object.class)); }/** * Determine if STR is an instance of the object class * is print true * No print false */public static void TestInstanceOf1 () {str ing str = new String (); System.out.print ("Str is an instance of object:"); System.out.println (str instanceof Object); }/** * Determines if O is an instance of the object class * Yes print true * No print false */public static void TestInstanceOf2 () {Object o = new Object (); System.out.print ("O is an instance of object:"); System.out.println (o instanceof Object); } public static void Main (string[] args) {testIsAssignedFrom1 (); TestIsAssignedFrom2 (); TestIsAssignedFrom3 (); TESTINSTANCEOF1 (); TestInstanceOf2 (); }}Results:
String is the parent class of object: False
object is the parent class of string: True
Object and object are the same: true
STR is an instance of object: True
O is an instance of object: True
IsAssignableFrom () method in Java and instanceof () method usage