Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

java - Casting a Spring's Proxy object to the actual runtime class

I'm using Spring, at one point I would like to cast the object to its actual runtime implementation.

Example:

Class MyClass extends NotMyClass {
    InterfaceA a;
    InterfaceA getA() { return a; }

    myMethod(SomeObject o) { ((ImplementationOfA) getA()).methodA(o.getProperty()); }
}

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 .

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.

EDIT 2

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 know it is not very elegant but works.

All credits to http://www.techper.net/2009/06/05/how-to-acess-target-object-behind-a-spring-proxy/ Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For me version from EDIT 2 didn't worked. Below one worked:

@SuppressWarnings({"unchecked"})
protected <T> T getTargetObject(Object proxy) throws Exception {
    while( (AopUtils.isJdkDynamicProxy(proxy))) {
        return (T) getTargetObject(((Advised)proxy).getTargetSource().getTarget());
    }
    return (T) proxy; // expected to be cglib proxy then, which is simply a specialized class
}

Usage:

    UserServicesImpl serviceImpl = getTargetObject(serviceProxy);
    serviceImpl.setUserDao(userDAO);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...