I am using Spring to inject beans. And I am using some annotations to annotate bean methods (Security, TransactionManagement, ExceptionHanling, Logging). The problem is:
I want to create JUnit test to check if I forgot annotate some methods. But Spring returns $ProxyXXX class without any annotations on methods..
Method[] methods = logic.getClass().getMethods();
for (Method method : methods) {
Annotation[] annotations = method.getAnnotations(); // empty array!
How can I get annotations for method or obtain a real class object?
P.S. Spring 2.5.6, JDKDynamicProxy (not CGLib)
Spring's interface-based proxies implement TargetClassAware
.
You can cast the proxied object to get the object and class it acts as a proxy for (see TargetSource):
Advised advised = (Advised) proxy;
Class<?> cls = advised.getTargetSource().getTargetClass();
Generally you should follow the Spring principles and keep obtaining the correct class as unobtrusive as possible. Meaning that as little classes as possible should depend on the Spring Framework APIs (maybe add a ClassLocator and a SpringProxyClassLocator implementation).
Or you can just call: AopUtils.getTargetClass(java.lang.Object) It is a static
method call.
来源:https://stackoverflow.com/questions/2289211/obtain-real-class-object-for-spring-bean