3

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.

4
  • How would an exception get thrown that isn't even included in your project? Commented Sep 4, 2019 at 12:54
  • 2
    Why exactly are you writing such a method? This looks like bad design. Also what daniu said. The exception either exists in your project or not. If it doesn't exist, then you won't need to handle it (as the exception can't exist without its class). If it does exist, you can refer to it by name. Commented Sep 4, 2019 at 12:55
  • It's a big and complicated project with a large number of modules. All exceptions including the lost one wrapped somewhere else in code inside other class as a Throwable. I found that it is present in logs so I need to filter it. Commented Sep 4, 2019 at 13:03
  • 1
    Conceptually you are now using info from an other module. If you cannot switch from blacklist to whitelist or vice versa, you could add one or more marker interfaces in a common module, add the interface to the other modules' exceptions, and do one single cause instanceof IsLogged. It removes the magic of checking for (foreign) class names. Commented Sep 4, 2019 at 13:39

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.