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

时间:2023-12-10 16:48:14

源码:

 /**
* @Date:2018-04-20
* @Description:判断Instance
* - instanceof方法返回一个boolean类型的值,意在告诉我们对象是不是某个特定的类型实例。
* - isInstance方法则是Class类中的一个Native方法,也是用于判断对象类型的。
**/
public class InstanceDemo { static void test(Object x) {
System.out.println("Testing x of type " + x.getClass());
System.out.println("x instanceof A " + (x instanceof A));
System.out.println("x instanceof B " + (x instanceof B));
System.out.println("A.isInstance(x) " + A.class.isInstance(x));
System.out.println("B.isInstance(x) " +
B.class.isInstance(x));
System.out.println("x.getClass() == A.class " +
(x.getClass() == A.class));
System.out.println("x.getClass() == B.class " +
(x.getClass() == B.class));
System.out.println("x.getClass().equals(A.class)) " +
(x.getClass().equals(A.class)));
System.out.println("x.getClass().equals(B.class)) " +
(x.getClass().equals(B.class)));
} public static void main(String[] args) {
test(new A());
System.out.println("-------------------------");
test(new B());
} } class A {
} class B extends A {
}

运行结果:

 Testing x of type class org.study2.reflection.A
x instanceof A true
x instanceof B false
A.isInstance(x) true
B.isInstance(x) false
x.getClass() == A.class true
x.getClass() == B.class false
x.getClass().equals(A.class)) true
x.getClass().equals(B.class)) false
-------------------------
Testing x of type class org.study2.reflection.B
x instanceof A true
x instanceof B true
A.isInstance(x) true
B.isInstance(x) true
x.getClass() == A.class false
x.getClass() == B.class true
x.getClass().equals(A.class)) false
x.getClass().equals(B.class)) true