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:
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)
PackageCom.bill99.pattern; Public classAssignabletest { Publicassignabletest (String name) {}/*** Determine if a class is the parent of another class * is print true * No print false*/ Public Static voidtestIsAssignedFrom1 () {System.out.println ("String is the parent class of object:" +string.class. IsAssignableFrom (Object.class)); } /*** Determine if a class is the parent of another class * is print true * No print false*/ Public Static voidtestIsAssignedFrom2 () {System.out.println ("Object is the parent of string:" +object.class. IsAssignableFrom (String.class)); } /*** Determine if a class is the same as another class * is print true * No print false*/ Public Static voidtestIsAssignedFrom3 () {System.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 voidtestInstanceOf1 () {String str=NewString (); System.out.print ("Str is an instance of object:"); System.out.println (strinstanceofObject); } /*** Determine if O is an instance of the object class * is print true * No print false*/ Public Static voidTestInstanceOf2 () {Object o=NewObject (); System.out.print ("O is an instance of object:"); SYSTEM.OUT.PRINTLN (oinstanceofObject); } Public Static voidMain (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