Sophisticated way to get if exception is instanceof without using instanceof

Fyodor Iz :

I'm writing a method that will return true if exception is instance of *someClass*. But I can't import one of the classes because it is in another module. I can't add that module to the project, so I guess, I cant use instanceof.

I consider creating a Map of Strings - exception's classnames and check if my exception's classname is in the map, but I think it would be rather slow and ugly.

Method looks like:

public boolean checkExceptionClass(Throwable cause){
 return (cause instanceof firstException
         || cause instanceof secondException
         || cause instanceof iDontHaveThatClassException // can't do that
         || cause instanceof fourthException);
}

Maybe I don't see good solution to that problem right under my nose. Any ideas and advices are much appreciated.

Uri Loya :

You can try using .getClass() and getSimpleName(), for example:

Integer integer = Integer.valueOf(1);

if(integer.getClass().getSimpleName().equals("Integer") {
 return true
}

so basically you can use the name of the class you can't import, worth mentioning that hard coding is not the best practice

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=148368&siteId=1