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

前端 未结 17 900
梦毁少年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.

    0 讨论(0)
  • 2020-11-22 03:40

    It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.

    Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).

    instanceof is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.

    if (obj instanceof Checkbox)
    {
        Checkbox cb = (Checkbox)obj;
        boolean state = cb.getState();
    }
    
    0 讨论(0)
  • 2020-11-22 03:41

    Best explanation is jls. Always try to check what source says. There you will get the best answer plus much more. Reproducing some parts here:

    The type of the RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs.

    It is a compile-time error if the ReferenceType mentioned after the instanceof operator does not denote a reference type that is reifiable (§4.7).

    If a cast (§15.16) of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

    0 讨论(0)
  • 2020-11-22 03:42

    This operator allows you to determine the type of an object. It returns a boolean value.

    For example

    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));
        }
    } 
    

    the output is:

    Returns a boolean value true
    Returns a boolean value true
    Returns a boolean value true
    Returns a boolean value false
    
    0 讨论(0)
  • 2020-11-22 03:43

    instanceof keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.

    Imagine:

    interface Domestic {}
    class Animal {}
    class Dog extends Animal implements Domestic {}
    class Cat extends Animal implements Domestic {}
    

    Imagine a dog object, created with Object dog = new Dog(), then:

    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
    

    However, with Object animal = new Animal();,

    animal instanceof Dog // false
    

    because Animal is a supertype of Dog and possibly less "refined".

    And,

    dog instanceof Cat // does not even compile!
    

    This is because Dog is neither a subtype nor a supertype of Cat, and it also does not implement it.

    Note that the variable used for dog above is of type Object. This is to show instanceof is a runtime operation and brings us to a/the use case: to react differently based upon an objects type at runtime.

    Things to note: expressionThatIsNull instanceof T is false for all Types T.

    Happy coding.

    0 讨论(0)
  • 2020-11-22 03:45

    The instanceof operator compares an object to a specified type. 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.

    http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

    0 讨论(0)
提交回复
热议问题