Java中使用的'instanceof'运算符是什么?

Ben*_*Ben 157 java instanceof

什么是instanceof用于操作?我见过像这样的东西

if (source instanceof Button) {
    //...
} else {
    //...
}
Run Code Online (Sandbox Code Playgroud)

但这对我来说都没有意义.我已完成了我的研究,但仅提供了没有任何解释的例子.

小智 222

instanceofkeyword是一个二元运算符,用于测试对象(实例)是否是给定Type的子类型.

想像:

interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}
Run Code Online (Sandbox Code Playgroud)

想象一下,创建一个dog 对象Object dog = new Dog(),然后:

dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal   // true - Dog extends Animal
dog instanceof Dog      // true - Dog is Dog
dog instanceof Object   // true - Object is the parent type of all objects
Run Code Online (Sandbox Code Playgroud)

然而,有了Object animal = new Animal();,

animal instanceof Dog // false
Run Code Online (Sandbox Code Playgroud)

因为它Animal是一种超级类型,Dog可能不那么"精致".

和,

dog instanceof Cat // does not even compile!
Run Code Online (Sandbox Code Playgroud)

这是因为Dog既不是子类型也不是超类型Cat,也不实现它.

请注意,dog上面使用的变量是类型Object.这是为了显示instanceof一个运行时操作并将我们带到一个/用例:在运行时根据对象类型做出不同的反应.

注意事项:expressionThatIsNull instanceof T所有类型都是假的T.

快乐的编码.

  • 我刚试过 - `Object dog = new Dog(); System.out.println(dog instanceof Cat);`.编译得很好并打印"假".编译器不允许在编译时确定`dog`不能是Cat(根据JLS中的规则) (13认同)
  • @FelixS您需要再次阅读答案.答案是关于`Object indirect = ...; if(间接instanceof Something)`.它不是关于`if(literal instanceof Something)`就像你似乎在假设的那样. (2认同)
  • @ErwinBolwidt 哦,对了,我一定跳过了“对象狗”部分。我的错! (2认同)

Mic*_*tta 44

如果表达式的左侧是右侧类名的实例,则它是一个返回true的运算符.

这样想吧.说你街区的所有房屋都是用相同的蓝图建造的.十个房屋(物体),一套蓝图(类定义).

instanceof当你有一个对象集合并且你不确定它们是什么时,它是一个有用的工具.假设您在表单上有一组控件.您想要读取任何复选框的已检查状态,但是您不能要求普通旧对象检查其已检查状态.相反,您将看到每个对象是否为复选框,如果是,则将其强制转换为复选框并检查其属性.

if (obj instanceof Checkbox)
{
    Checkbox cb = (Checkbox)obj;
    boolean state = cb.getState();
}
Run Code Online (Sandbox Code Playgroud)

  • 也就是说,使用`instanceof`可以使向下传播安全. (14认同)

fir*_*w52 29

本网站所述:

instanceof操作员可以被用来测试对象是否是特定类型的...

if (objectReference instanceof type)
Run Code Online (Sandbox Code Playgroud)

一个简单的例子:

String s = "Hello World!"
return s instanceof String;
//result --> true
Run Code Online (Sandbox Code Playgroud)

但是,应用instanceofnull引用变量/ expression会返回false.

String s = null;
return s instanceof String;
//result --> false
Run Code Online (Sandbox Code Playgroud)

由于子类是其超类的"类型",您可以使用它 instanceof来验证这个...

class Parent {
    public Parent() {}
}

class Child extends Parent {
    public Child() {
        super();
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        System.out.println( child instanceof Parent );
    }
}
//result --> true
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!


Dan*_*ite 14

如果source是一个object变量,instanceof是一种检查是否是一个变量的方法Button.


Pur*_*wal 14

此运算符允许您确定对象的类型.它返回一个boolean值.

例如

package test;

import java.util.Date;
import java.util.Map;
import java.util.HashMap;

public class instanceoftest
{
    public static void main(String args[])
    {
        Map m=new HashMap();
        System.out.println("Returns a boolean value "+(m instanceof Map));
        System.out.println("Returns a boolean value "+(m instanceof HashMap));
        System.out.println("Returns a boolean value "+(m instanceof Object));
        System.out.println("Returns a boolean value "+(m instanceof Date));
    }
} 
Run Code Online (Sandbox Code Playgroud)

输出是:

Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false
Run Code Online (Sandbox Code Playgroud)


Ada*_*kin 5

正如其他答案中提到的, 的典型典型用法instanceof是检查标识符是否指代更具体的类型。例子:

Object someobject = ... some code which gets something that might be a button ...
if (someobject instanceof Button) {
    // then if someobject is in fact a button this block gets executed
} else {
    // otherwise execute this block
}
Run Code Online (Sandbox Code Playgroud)

但是请注意,左侧表达式的类型必须是右侧表达式的父类型(参见JLS 15.20.2Java Puzzlers, #50, pp114)。例如,以下将无法编译:

public class Test {
    public static void main(String [] args) {
        System.out.println(new Test() instanceof String); // will fail to compile
    }
}
Run Code Online (Sandbox Code Playgroud)

这无法与消息编译:

Test.java:6: error: inconvertible types
        System.out.println(t instanceof String);
                       ^
  required: String
  found:    Test
1 error
Run Code Online (Sandbox Code Playgroud)

由于Test不是String. OTOH,这可以完美编译false并按预期打印:

public class Test {
    public static void main(String [] args) {
        Object t = new Test();
        // compiles fine since Object is a parent class to String
        System.out.println(t instanceof String); 
    }
}
Run Code Online (Sandbox Code Playgroud)