- instance 关注的是实例是否为类或接口的一个实例
- isAssignableFrom 关注的是Class对象是否相同,或者Class1是Class2的超类或接口
- Class1.isAssignableFrom(Class2)
一、验证代码如下
package com.cctest.veritydemo;
/**
* @author: gkyang
* @date: 2019-03-05
* @description:
*/
interface ClassDemoInteface {
}
class ClassDemoParent {
}
public class ClassDemo extends ClassDemoParent implements ClassDemoInteface{
public static void main(String[] args) {
ClassDemo cd = new ClassDemo();
/* ----------- instance ------------*/
System.out.println(cd instanceof ClassDemo); // true
System.out.println(cd instanceof ClassDemoParent); // true
System.out.println(cd instanceof ClassDemoInteface); // true
System.out.println(cd instanceof Object);
/* ----------- isAssignableFrom ----------*/
System.out.println(ClassDemo.class.isAssignableFrom(ClassDemo.class)); // true
System.out.println(ClassDemo.class.isAssignableFrom(ClassDemoParent.class)); // false
System.out.println(ClassDemo.class.isAssignableFrom(ClassDemoInteface.class)); // false
System.out.println(ClassDemoParent.class.isAssignableFrom(ClassDemo.class)); // true
System.out.println(ClassDemoInteface.class.isAssignableFrom(ClassDemo.class)); // true
}
}
努力做一名出色的技术人!