重温 Thinking in Java 7 - instanceof vs Class equivalence

instanceof vs Class equivalence

 

/*
	When you are querying for type information, there's an important different between either form of instanceof(that is, instanceof or
	isInstance(), which produce equivalent results) and the direct comparison of the Class objects. Here's an example that demonstrates
	the difference.
*/

class Base {
}

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)));
		System.out.println();
	}
	
	public static void main(String[] args){
		test(new Base());
		test(new Derived());
	}
}
/* Output:
Testing x of type class 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 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

Reassuringly, instanceof and isInstance() produce exactly the same results, as do equals() and ==. But the tests themselves draw
different conclusions. In keeping with the concept of type, instanceof says, "Are you this class, or a class derived from this class?"
On the other hand, if you compare the actual Class objects using ==, there is no concern with inheritance - it's either the exact type
or it isn't.
*/
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值