instanceof keyword usage

后端 未结 8 2398
死守一世寂寞
死守一世寂寞 2021-02-14 10:21

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 11:08

    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

提交回复
热议问题