Proxy cannot be cast to CLASS

后端 未结 2 1828
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 17:51

I\'m using Spring for wiring dependencies specifically for DAO classes that use Hibernate, but I\'m getting an exception that has me puzzled:

$Proxy58 cannot be

2条回答
  •  日久生厌
    2021-02-01 18:19

    I was writing unit tests and needed to be able to stub out the DAOs for some calls. Per This guys post: http://www.techper.net/2009/06/05/how-to-acess-target-object-behind-a-spring-proxy/ I used his method provided:

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

    Then you can easily call it with the proxy and get the object behind the proxy and manipulate the objects in it directly as needed.

提交回复
热议问题