将Spring的Proxy对象转换为实际的运行时类 [英] Casting a Spring's Proxy object to the actual runtime class
问题描述
我正在使用Spring,有时我想将对象强制转换为实际的运行时实现。
I'm using Spring, at one point I would like to cast the object to its actual runtime implementation.
示例:
Class MyClass extends NotMyClass {
InterfaceA a;
InterfaceA getA() { return a; }
myMethod(SomeObject o) { ((ImplementationOfA) getA()).methodA(o.getProperty()); }
}
大喊 ClassCastException
因为 a
是一个 $ ProxyN
对象。虽然在beans.xml中我注入了一个类 ImplementationOfA
的bean。
That yells a ClassCastException
since a
is a $ProxyN
object. Although in the beans.xml I injected a bean which is of the class ImplementationOfA
.
编辑1
我扩展了一个类,我需要调用 ImplementationOfA中的方法
。所以我想我需要施展。该方法会收到一个参数。
EDIT 1
I extended a class and I need to call for a method in ImplementationOfA
. So I think I need to cast. The method receives a parameter.
编辑2
我最好扯掉它target class:
I better rip off the target class:
private T getTargetObject(Object proxy, Class targetClass) throws Exception {
while( (AopUtils.isJdkDynamicProxy(proxy))) {
return (T) getTargetObject(((Advised)proxy).getTargetSource().getTarget(), targetClass);
}
return (T) proxy; // expected to be cglib proxy then, which is simply a specialized class
}
I知道它不是很优雅但是很有效。
I know it is not very elegant but works.
所有学分 http://www.techper.net/2009/06/05/how-to-acess-target-object-behind-a-spring- proxy /
谢谢!
All credits to http://www.techper.net/2009/06/05/how-to-acess-target-object-behind-a-spring-proxy/ Thank you!
推荐答案
为什么需要演员?
关于 Spring代理使用情况这是一个很棒的文章,我建议你阅读,评论。
Why do you need to cast? About Spring proxy usage this is a great article, I suggest you to read it, comments as well.
以及 Spring AOP文档。
这篇关于将Spring的Proxy对象转换为实际的运行时类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!