Java 编程/关键字/instanceof
外观
instanceof
是一个关键字。
它检查一个对象引用是否是一个类型的实例,并返回一个布尔值;
<object-reference> instanceof
Object
对于所有非空对象引用将返回 true,因为所有 Java 对象都继承自 Object
。instanceof
如果 <object-reference> 是 null
,则始终返回 false
。
语法
<object-reference> instanceof
TypeName
例如
class Fruit
{
//...
}
class Apple extends Fruit
{
//...
}
class Orange extends Fruit
{
//...
}
public class Test
{
public static void main(String[] args)
{
Collection<Object> coll = new ArrayList<Object>();
Apple app1 = new Apple();
Apple app2 = new Apple();
coll.add(app1);
coll.add(app2);
Orange or1 = new Orange();
Orange or2 = new Orange();
coll.add(or1);
coll.add(or2);
printColl(coll);
}
private static String printColl( Collection<?> coll )
{
for (Object obj : coll)
{
if ( obj instanceof Object )
{
System.out.print("It is a Java Object and");
}
if ( obj instanceof Fruit )
{
System.out.print("It is a Fruit and");
}
if ( obj instanceof Apple )
{
System.out.println("it is an Apple");
}
if ( obj instanceof Orange )
{
System.out.println("it is an Orange");
}
}
}
}
|
运行程序
java Test
输出
"It is a Java Object and It is a Fruit and it is an Apple"
"It is a Java Object and It is a Fruit and it is an Apple"
"It is a Java Object and It is a Fruit and it is an Orange"
"It is a Java Object and It is a Fruit and it is an Orange"
请注意,instanceof
运算符也可以应用于接口。例如,如果上面的示例用接口增强了
interface Edible
{
//...
}
|
以及修改后的类以实现此接口
class Orange extends Fruit implements Edible
{
...
}
|
我们可以询问我们的对象是否可食用。
if ( obj instanceof Edible )
{
System.out.println("it is edible");
}
|