【课本】反射

instanceof:

判断一个引用类型变量所指向的对象是否是一个类(或接口、抽象类、父类)

  • 子类对象instanceof父类,返回true
  • 父类对象instanceof子类,返回false
  • 如果两个类不再同一个继承家族中,使用instanceof会出现错误
  • 数组类型也可以用instanceof比较
public class InstanceDemo {
    public static void typeOf(Object obj) {
        if(obj instanceof Student) {
            System.out.println("Student");
        }
        if(obj instanceof Person) {
            System.out.println("Person");
        }
    }

    public static void main(String[] args) {
        Person per1 = new Person("tom");
        Student stu1 = new Student("jack", 23);
        typeOf(per1);
        typeOf(stu1);//typeOf两条if语句都执行
        Person per2 = new Person("rose");
        Person per3 = new Student("white", 24);
        typeOf(per2);
        typeOf(per3);//typeOf两条if语句都执行

        //数组类型用instanceof比较
        String str[] = new String[2];
        if(str instanceof String[]) {
            System.out.println("true!"); //true
        }
    }
}

class Person {
    String name;
    public Person(){}
    public Person(String name){this.name = name;}
}

class Student extends Person {
    int age;
    public Student(){}
    public Student(String name, int age) {
        super(name);
        this.age = age;
    }
}
原文地址:https://www.cnblogs.com/wmjlh/p/7648983.html