instanceof、isInstance、==、equals判断Class是否相等

instanceof 关键字 和 isInstance的用法相同

现在有一个类Base

public class Base {

}

还有一个类Derived继承于Base

public class Derived extends Base{

}

再写一个类判断上述条件下两者是否相等

public class FamilyVsExactType {

	static void test(Object x) {
		System.out.println("Testing x of type=" + x.getClass());
		System.out.println("x instanceof Base=" + (x instanceof Base));
		System.out.println("x instanceof Derived=" + (x instanceof Derived));
		System.out.println("Base.isInstance(x)=" + Base.class.isInstance(x));
		System.out.println("Derived.isInstance(x)=" + Derived.class.isInstance(x));
		System.out.println("x.getClass() == Base.class=" + (x.getClass() == Base.class));
		System.out.println("x.getClass() == Derived.class=" + (x.getClass() == Derived.class));
		System.out.println("x.getClass.equals(Base.class)=" + (x.getClass().equals(Base.class)));
		System.out.println("x.getClass.equals(Derived.class)=" + (x.getClass().equals(Derived.class)));
		
	}
	
	public static void main(String[] args) {
		test(new Base());
		test(new Derived());
	}
}

== 和 equals比较的实际的Class类,没有考虑继承,instanceof 和 isInstance考虑继承

输出结果:

Testing x of type=class com.my.rest.six.Base

x instanceof Base=true

x instanceof Derived=false

Base.isInstance(x)=true

Derived.isInstance(x)=false

x.getClass() == Base.class=true

x.getClass() == Derived.class=false

x.getClass.equals(Base.class)=true

x.getClass.equals(Derived.class)=false

Testing x of type=class com.my.rest.six.Derived

x instanceof Base=true

x instanceof Derived=true

Base.isInstance(x)=true

Derived.isInstance(x)=true

x.getClass() == Base.class=false

x.getClass() == Derived.class=true

x.getClass.equals(Base.class)=false

x.getClass.equals(Derived.class)=true


引用自 《thinking in Java》第14章


发布了82 篇原创文章 · 获赞 526 · 访问量 12万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览