How do I get the underlying type of a proxy object in java?

前端 未结 7 1131
旧时难觅i
旧时难觅i 2020-12-09 02:05

I\'d like to access the classname of the underlying class which is an instance of java.lang.reflect.Proxy.

Is this possible?

7条回答
  •  清歌不尽
    2020-12-09 02:52

    I found a good solution on this site (now archived):

    @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
      }
    }
    

    Usage

    @Override
    protected void onSetUp() throws Exception {
      getTargetObject(fooBean, FooBeanImpl.class).setBarRepository(new MyStubBarRepository());
    }
    

提交回复
热议问题