isAssignableFrom & isInstance

本文详细介绍了 Java 中 Class 类的 isAssignableFrom 和 isInstance 方法。通过示例演示了如何判断一个类是否为另一个类的子类或实现接口,以及如何检查一个对象是否与指定类兼容。
摘要由CSDN通过智能技术生成
java.lang.Object extended by [b]java.lang.Class[/b]
[list]
[*]boolean [b]isAssignableFrom[/b](Class cls) : Determines if the class or interface represented by this Class object is [color=red]either the same as, or is a superclass or superinterface of, the class or interface[/color] represented by the specified Class parameter.
[*]boolean [b]isInstance[/b](Object obj) : Determines if the specified Object is assignment-compatible with the object represented by this Class.
[/list]

isAssignableFrom接受的是Class参数,isInstance接受的是Object参数。

System.out.println("Object.class.isAssignableFrom(String.class) = " + Object.class.isAssignableFrom(String.class));
System.out.println("Object.class.isAssignableFrom(Object.class) = " + Object.class.isAssignableFrom(Object.class));
System.out.println("String.class.isAssignableFrom(Object.class) = " + String.class.isAssignableFrom(Object.class));

String s = "";
Object o = new Object();
System.out.println("Object.class.isInstance(s) = " + Object.class.isInstance(s));
System.out.println("Object.class.isInstance(o) = " + Object.class.isInstance(o));
System.out.println("String.class.isInstance(o) = " + String.class.isInstance(o));

[b]执行结果:[/b]
Object.class.isAssignableFrom(String.class) = true
Object.class.isAssignableFrom(Object.class) = true
String.class.isAssignableFrom(Object.class) = false
Object.class.isInstance(s) = true
Object.class.isInstance(o) = true
String.class.isInstance(o) = false
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值