Why can't a “Class” variable be passed to instanceof?

后端 未结 4 1807
礼貌的吻别
礼貌的吻别 2020-12-02 17:56

Why doesn\'t this code compile?

    public boolean isOf(Class clazz, Object obj){
        if(obj instanceof clazz){
            return true;
        }else{
          


        
4条回答
  •  情深已故
    2020-12-02 18:38

    Firstly, instanceof requires that the operand on the right is an actual class (e.g. obj instanceof Object or obj instanceof Integer) and not a variable of type Class. Secondly, you have made a fairly common newbie mistake that you really should not do... the following pattern:

    if ( conditional_expression ){
        return true;
    } else{
        return false;
    }
    

    The above can be refactored into:

    return conditional_expression;
    

    You should always perform that refactoring, as it eliminates a redundant if...else statement. Similarly, the expression return conditional_expression ? true : false; is refactorable to the same result.

提交回复
热议问题