0

I am trying to validate the values returned by a list of methods using java reflection and @PostConstruct spring annotation as it is depicted in the following code snippet :

@Service("appConfigService")
public class AppConfigServiceImpl implements AppConfigService{       

    //rest of source code including constructor and other methods is omitted 

    @Override
    public String getServerURL(){//example of a method I am invoking in the postConstruct phase
       //method body omitted
    }

    @PostConstruct
    public void postConstruct() {
        try {
            Class<AppConfigServiceImpl> classObject = AppConfigServiceImpl.class;
            AppConfigServiceImpl appConfigServiceImpl = classObject.newInstance();
            Method[] methods = classObject.getMethods();
            for(Method method: methods)     
                method.invoke(appConfigServiceImpl);            
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
        }
    }
}

However when spring executes the postConstruct() method a java.lang.reflect.InvocationTargetException is thrown. I could not figure out the source of the exception. Any help will be more than welcome.

ecdhe
  • 421
  • 4
  • 17
  • You can try to unwrap the InvocationTargetException and examine it's base cause. Why don't you try to retrieve the target exception and see if that helps? Check the link below: https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/InvocationTargetException.html#getTargetException() Also, I suppose that the code sample is not something that you copy-pasted. If this is the case, then the @Service annotation is misspelled. – akortex Dec 12 '17 at 10:03
  • @Aris : I have tried to unwrap the caught InvocationTargetException using both : e.getCause().getStacktrace() and e.getCause().getMessage(). The first command returns a toString() representation of a StackTraceElement object ([Ljava.lang.StackTraceElement;@6498bbf9) while the latter returns null. This does not help that much. Any furher hints please? – ecdhe Dec 12 '17 at 10:30
  • Your catch clause uses a bitwise operation to catch all the type of exceptions you have defined in there in a single cause. While this will work fine for logging purposes (i.e a printStacktrace) it will not permit you to actually examine the base cause of the invocation exception. Either change the catch clause to a multicatch, catch the InvocationException and use InvocationTargetException# getTargetException to retrieve the actual cause, or do an instanceof to check the caught exception type, cast it an InvocationTargetException and then do the above mentioned. – akortex Dec 12 '17 at 10:40

0 Answers0