Try making a static shared helper function to implement your custom getMessage:
class MyException extends Exception {
....
public String getMessage() {
return ExceptionHelper.getMessage(this);
}
}
class MyRuntimeException extends RuntimeException {
....
public String getMessage() {
return ExceptionHelper.getMessage(this);
}
}
class ExceptionHelper {
public static String getMessage(Exception e) {
// your shared impl here
}
}
Edit - if your Exception subclasses have more than just an impl of getMessage
copy-pasted between them, you may want to share that as well. A slight tweak of the above to turn the static helper into an encapsulated class will handle this well.
For example: create a class named something like ExceptionDetails
, where this shared code and variables (and any other duplication) could live, and each Exception subclass would have their own instance of ExceptionDetails
.