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

前端 未结 17 1231
梦毁少年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:39

    The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).

    The instanceof in java is also known as type comparison operator as it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.

    From JDK 14+ which includes JEP 305 we can also do "Pattern Matching" for instanceof

    Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type. Pattern matching allows a more clear and efficient expression of common logic in a system, namely the conditional removal of components from objects.

    Before Java 14

    if (obj instanceof String) {
        String str = (String) obj; // need to declare and cast again the object
        .. str.contains(..) ..
    }else{
         str = ....
    }
    

    Java 14 enhancements

    if (!(obj instanceof String str)) {
        .. str.contains(..) .. // no need to declare str object again with casting
    } else {
        .. str....
    }
    

    We can also combine the type check and other conditions together

    if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}
    

    The use of pattern matching in instanceof should reduce the overall number of explicit casts in Java programs.

    PS: instanceOf will only match when the object is not null, then only it can be assigned to str.

提交回复
热议问题