java中,instanceof运算符的前一个操作符是一个引用变量,后一个操作数通常是一个类(可以是接口),用于判断前面的对象是否是后面的类,或者其子类、实现类的实例。如果是返回true,否则返回false。
public class One
{
public static void main(String[] args) {
One o = new One();
if (o instanceof One) //o是One类的实例
{
System.out.println("yes"); //输出yes
}
}
}
继续:
interface Two
{
void say();
}
class Three implements Two
{
public void say()
{
System.out.println("oh bo vcccbb ");
}
}
public class One
{
public static void main(String[] args) {
Two two = new Three();
if (two instanceof Three) //下面输出yes
{
System.out.println("yes");
}
else
{
System.out.println("no");
}
/*在编译时,two是Two类型的,Two类型和Three接口类型存在实现关系,所以编译通过
运行时,two表现为Three类型,是Three类的一个实例,输出yes
*/
}
}
用来判断一个类的类型:
if (anObject instanceof String){}
检测anObject是否为String类型。
出现编译错误的情况:
class Two
{
public void say()
{
System.out.println("so great");
}
}
class Three extends Two
{
public void say()
{
System.out.println("oh bo vcccbb ");
}
}
class Four extends Two
{
public void say()
{
System.out.println("no bbbbbbbb");
}
}
public class One1
{
public static void main(String[] args) {
Two two = new Three();
if (two instanceof Four)
{
System.out.println("yes");
}
else
{
System.out.println("no"); //输出no
}
/*
上面的代码运行的结果为no,编译时two的类型Two和Four之间是继承关系,编译通过
运行时,two引用的是一个Three类的实例,不是Four的实例,所以结果为no
*/
/*注释掉上面8行代码,运行下面的代码,出现编译错误*/
if (two instanceof One1)
{
System.out.println("yes1");
}
else
{
System.out.println("no1");
}
/*reason:
编译时,two的Two类型和One1类没有任何继承(extends)、实现(implements)关系,所以你不能想当然的就去进行比较,出现编译错误
*/
}
}
总结:instanceof运算符的左边操作数的编译类型和右边的类之间,要么相同,要么是具有父子继承关系,要么有接口的实现关系,否则会引起编译错误。instanceof关键字对于类与类之间和类与接口之间,进行转型的一个安全的控制。