Java之"instanceof"和"isInstance"代码举例

 源码:

 1 /**
 2  * @Date:2018-04-20
 3  * @Description:判断Instance
 4  * - instanceof方法返回一个boolean类型的值,意在告诉我们对象是不是某个特定的类型实例。
 5  * - isInstance方法则是Class类中的一个Native方法,也是用于判断对象类型的。
 6  **/
 7 public class InstanceDemo {
 8 
 9     static void test(Object x) {
10         System.out.println("Testing x of type " + x.getClass());
11         System.out.println("x instanceof A " + (x instanceof A));
12         System.out.println("x instanceof B " + (x instanceof B));
13         System.out.println("A.isInstance(x) " + A.class.isInstance(x));
14         System.out.println("B.isInstance(x) " +
15                 B.class.isInstance(x));
16         System.out.println("x.getClass() == A.class " +
17                 (x.getClass() == A.class));
18         System.out.println("x.getClass() == B.class " +
19                 (x.getClass() == B.class));
20         System.out.println("x.getClass().equals(A.class)) " +
21                 (x.getClass().equals(A.class)));
22         System.out.println("x.getClass().equals(B.class)) " +
23                 (x.getClass().equals(B.class)));
24     }
25 
26     public static void main(String[] args) {
27         test(new A());
28         System.out.println("-------------------------");
29         test(new B());
30     }
31 
32 }
33 
34 class A {
35 }
36 
37 class B extends A {
38 }

 运行结果:

 1 Testing x of type class org.study2.reflection.A
 2  x instanceof A true
 3  x instanceof B false
 4  A.isInstance(x) true
 5  B.isInstance(x) false
 6  x.getClass() == A.class true
 7  x.getClass() == B.class false
 8  x.getClass().equals(A.class)) true
 9  x.getClass().equals(B.class)) false
10  -------------------------
11  Testing x of type class org.study2.reflection.B
12  x instanceof A true
13  x instanceof B true
14  A.isInstance(x) true
15  B.isInstance(x) true
16  x.getClass() == A.class false
17  x.getClass() == B.class true
18  x.getClass().equals(A.class)) false
19  x.getClass().equals(B.class)) true

 

posted @ 2018-04-20 11:32  星瑞  阅读(254)  评论(0编辑  收藏  举报