java 继承关系判断


继承关系判断

  • Class.java # public native boolean isInstance(Object obj);

    // true
    System.out.println(childType.isInstance(childObject));
    // true
    System.out.println(parentType.isInstance(childObject));
    // false
    System.out.println(childType.isInstance(parentObject));
    

    说明:

    • 参数obj的参数类型若为.class,返回 false
    • 当参数强转为调用者对象不会报异常时,返回true(即调用者为参数的类或父类)
  • Class.java#public native boolean isAssignableFrom(Class<?> cls);

    调用者和参数都是.class类型;参数是调用者的子类时为true

    // true
    System.out.println(parentType.isAssignableFrom(childType));
    
  • instance of 关键字

    用法:A isntance of B:判断左边对象是否是右边的实例;

    @Test
    public void test3() {
        Child1 childObject = new Child1();
        Parent1 parentObject = new Parent1();
        // true
        System.out.println(childObject instanceof Parent1);
        // false
        System.out.println(parentObject instanceof Child1);
    }
    


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM