0

Background:

I have hundreds of XXXFaultMsg classes generated from a WSDL file, they all have a method getFaultMsg() but they are extended from Exception directly. I have a function with argument Exception e, where e might be instance of one of the XXXFaultMsg classes.

Challenge:

I want to invoke getFaultMsg() on e if it is an instance of XXXFaultMsg.

I have written if (e.getClass().getName().endsWith("FaultMsg")) to detect whether e is an instance of XXXFaultMsg. Then how can I declare a var with type XXXFaultMsg and cast e to it and call getFaultMsg() on it?

P.S. I don't want to construct a long list of if (e instanceof XXXFaultMsg) cause there are over 100 XXXFaultMsg classes.

4
  • 3
    but they are extended from Exception directly time to refactor maybe Commented Jan 27, 2017 at 0:32
  • The solution here is to fix the generation. Commented Jan 27, 2017 at 0:34
  • If you're not able to restructure the classes, you would have to use reflection to call the method. Commented Jan 27, 2017 at 0:36
  • They are WebService client stubs generated from WSDL by JAX-WS and the WSDL file is provided other people. Commented Jan 27, 2017 at 0:43

1 Answer 1

3

Say you have one method which takes no args:

Method methodToFind = null;
if (e.getClass().getName().endsWith("FaultMsg")){
    try {
      methodToFind = e.getClass().getMethod("getFaultMsg", (Class<?>[]) null);
    } catch (NoSuchMethodException | SecurityException e) {
      // Your exception handling goes here
    }
}

Invoke it if present:

if(methodToFind == null) {
   // Method not found.
} else {
   // Method found. You can invoke the method like
   methodToFind.invoke(e, (Object[]) null);
}
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.