instanceof keyword usage

后端 未结 8 2274
野性不改
野性不改 2021-02-14 10:44

Is using the instanceof keyword against the essence of object oriented programming? I mean is it a bad programming practice? I read somewhere that us

8条回答
  •  心在旅途
    2021-02-14 10:50

    Another usage of instaceOf operation could be error handling. If you have similar error handling for exceptions, and you want to have it all in one place you can use:

    public void handleError(Throwable t, HttpServletRequest req) {
       if (t instaceOf ValidationException) {
                  ...doSomewthing......
       } else    if (t instaceOf DataException) {
                  ...doSomewthing......
       } else    if (t instaceOf DataException) {
                  ...doSomewthing......
       } else {
                  ...doSomewthing......
       }
    
    }
    

    with above code, you avoid to have many

    } catch  {
    

    blocks and instead have just one

    } catch (Throwable t) {
       handleError(t, request);
       return "errorPage" or whateveryouwant;
    }
    

    Also, one more thing is, is you check java source code, you will find so many usages of instaceof..

    And one good link: article about usage of instaceof

提交回复
热议问题