jeudi 26 janvier 2017

Convert an Object instance to the real subclass instance dynamically

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.





Aucun commentaire:

Enregistrer un commentaire