What is the 'instanceof' operator used for in Java?

前端 未结 17 1215
梦毁少年i
梦毁少年i 2020-11-22 03:03

What is the instanceof operator used for? I\'ve seen stuff like

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

17条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 03:58

    Most people have correctly explained the "What" of this question but no one explained "How" correctly.

    So here's a simple illustration:

    String s = new String("Hello");
    if (s instanceof String) System.out.println("s is instance of String"); // True
    if (s instanceof Object) System.out.println("s is instance of Object"); // True
    //if (s instanceof StringBuffer) System.out.println("s is instance of StringBuffer"); // Compile error
    Object o = (Object)s;
    if (o instanceof StringBuffer) System.out.println("o is instance of StringBuffer"); //No error, returns False
    else System.out.println("Not an instance of StringBuffer"); // 
    if (o instanceof String) System.out.println("o is instance of String"); //True
    

    Outputs:

    s is instance of String
    s is instance of Object
    Not an instance of StringBuffer
    o is instance of String
    

    The reason for compiler error when comparing s with StringBuffer is well explained in docs:

    You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

    which implies the LHS must either be an instance of RHS or of a Class that either implements RHS or extends RHS.

    How to use use instanceof then?
    Since every Class extends Object, type-casting LHS to object will always work in your favour:

    String s = new String("Hello");
    if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //No compiler error now :)
    else System.out.println("Not an instance of StringBuffer");
    

    Outputs:

    Not an instance of StringBuffer
    

提交回复
热议问题