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

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

    Instance of keyword is helpful when you want to know particular object's instance .

    Suppose you are throw exception and when you have catch then perform sum custom operation and then again continue as per your logic (throws or log etc)

    Example : 1) User created custom exception "InvalidExtensionsException" and throw it as per logic

    2) Now in catch block catch (Exception e) { perform sum logic if exception type is "InvalidExtensionsException"

    InvalidExtensionsException InvalidException =(InvalidExtensionsException)e;
    

    3) If you are not checking instance of and exception type is Null pointer exception your code will break.

    So your logic should be inside of instance of if (e instanceof InvalidExtensionsException){ InvalidExtensionsException InvalidException =(InvalidExtensionsException)e; }

    Above example is wrong coding practice However this example is help you to understand use of instance of it.

提交回复
热议问题