jeudi 5 août 2021

`getDeclaredMethods()` doesn't show private methods declared inside a Spring Framework based class

I'm making use of Spring Framework's Open Service Broker API implementation. I've implemented ServiceInstanceService interface in order to create methods for service provisioning. I'm trying to create a few private methods in the same class, which I wish to invoke later on Java's Reflection API. However, these methods are non-discoverable through the getDeclaredMethods() call.

//ServiceProvider.java

@Service
public class ServiceProvider implements ServiceInstanceService {

    @SomeAnnotation
    private void methodA () {
       // .. some code
    }

}
//SomeOtherClass.java

@Service
public class SomeOtherClass {

    @Autowired
    ServiceProvider serviceProvider;

    private void invoker () {
        Class<?> className = serviceProvider.getClass();
        for (Method method : className.getDeclaredMethods()) {
             System.out.println(method.getName());
             if (method.isAnnotationPresent(SomeAnnotation.class)) {
                 method.setAccessible(true);
                 try {
                     method.invoke(serviceProvider);
                 } catch (SomeException e) {
                     // .. do something about the exception
                 }
        }
    }
}

I know that I could've searched for methodA by it's name, however my problem statement forces me to detect and invoke methods annotated with SomeAnnotation, thus the above approach. Also, at least methodA should have printed out even if, let's say my annotation based check fails. But it doesn't happen. Only the public methods are printed out. This behavior is a bit different than what is claimed in the documentation.

What could be the possible issue in my code that masks methodA from Reflection API?





Aucun commentaire:

Enregistrer un commentaire