Cannot find the Type of class to use with instanceOf
I am creating an annotation where I need to match the root cause and then take action. The three classes are passed in the array as fully qualified names like javax.persistence.PersistenceException. When I use these classes in the "instanceOf" which accepts type of the class to match the rootCause, it does not work. I get an error "class0 cannot be resolved to a type". I also tried class0.getClass() to find the Type. Any advise will be appreciated.
public boolean findRootCauseOfException(Throwable throwable, String[] value) {
Objects.requireNonNull(throwable);
Throwable rootCause = throwable;
Object class0 = null;
Object class1 = null;
Object class2 = null;
try {
class0 = Class.forName(value[0]);
class1 = Class.forName(value[1]);
class2 = Class.forName(value[2]);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
while (rootCause != null) {
if (rootCause instanceof class0
|| rootCause instanceof class1
|| rootCause instanceof class2 ) {
return true;
}
rootCause = rootCause.getCause();
}
return false;
}
Solution 1:
instanceof
only works with literal classes, not with Class
objects.
Class.isInstance
You must call the isInstance
method on Class
class. Do not confuse with instanceOf
.
class0.isInstance(rootCause)