开发者

How to get the name of a proxy class?

I'm using the java.util.concurre开发者_如何学Cncy framework for the first time. Here's a very simplified version of what I'm doing. For those not intimately familiar with the framework, future.get() executes a Callable object defined in the future. future.getOriginatingRequest() returns an object I set in the future for use by the Callable object and I'm just trying to log which originating request object failed (its enough to know the class name of it).

try {
  future.get();
} catch (ExecutionException e) {
  logger.error("Failed to execute future with id '" +
            future.getOriginatingRequest().getClass().getName() + "'");
}

The problem I'm having is that the logging framework is outputting this:

Failed to execute future with id '$Proxy22'

Thus instead of the real class name I am getting $Proxy22 or some other number. Is there a way to get ahold of the real class name rather than the proxy name? Bonus points is someone can clearly explain why I'm getting the proxy string in the first place!


I can answer the bonus question: the string is the name of a dynamic Proxy class, generated in runtime.

As for how you can get to the masked class, there's not even a guarantee that one exists at all. The only thing you can do is to call Proxy.getInvocationHandler() on your proxy object and hope that the invocation handler will reveal more information (unlikely but may be worth a shot).


I find good for me solution on http://www.techper.net/2009/06/05/how-to-acess-target-object-behind-a-spring-proxy/

@SuppressWarnings({"unchecked"})
protected <T> T getTargetObject(Object proxy, Class<T> 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());
}


i'm guessing that the proxy class is a subclass of the class you're looking for. especially if the class you're looking for is a class you wrote.

can you access the inheritance tree for the object you found? maybe through reflection?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜