Why doesn\'t this code compile?
public boolean isOf(Class clazz, Object obj){
if(obj instanceof clazz){
return true;
}else{
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.