有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

“instanceof”操作符在Java中用于什么?

instanceof运算符用于什么?我见过这样的事

if (source instanceof Button) {
    //...
} else {
    //...
}

但这些对我来说都没有意义。我做过研究,但只举了一些例子,没有任何解释


共 (3) 个答案

  1. # 1 楼答案

    正如其他答案中提到的,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
    }
    

    但是请注意,左侧表达式的类型必须是右侧表达式的父类型(请参见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
        }
    }
    

    这无法编译,并显示以下消息:

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

    因为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); 
        }
    }
    
  2. # 2 楼答案

    此运算符允许您确定对象的类型。 它返回一个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));
        }
    } 
    

    输出为:

    Returns a boolean value true
    Returns a boolean value true
    Returns a boolean value true
    Returns a boolean value false
    
  3. # 3 楼答案

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