Luk*_*der 6 java reflection bytecode proxy-classes
为了更好的调试,我经常希望:
Exception
at com.example.blah.Something.method()
at com.example.blah.Xyz.otherMethod()
at com.example.hello.World.foo()
at com.example.debug.version_3_8_0.debug_info_something.Hah.method() // synthetic method
at com.example.x.A.wrappingMethod()
Run Code Online (Sandbox Code Playgroud)
如上所示的调试堆栈帧将动态生成,就像a一样java.lang.reflect.Proxy
,除了我想完全控制最终在代理上的完整限定方法名称.
在通话网站上,我会做一些愚蠢而简单的事情:
public void wrappingMethod() {
run("com.example.debug.version_3_8_0.debug_info_something.Hah.method()", () -> {
World.foo();
});
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这wrappingMethod()
是一个真正的方法,最终在堆栈跟踪上,Hah.method()
是一个动态生成的方法,而又World.foo()
是一个真正的方法.
是的,我知道这会污染已经很深的堆栈痕迹.别担心.我有我的理由.
是否有(简单)方法来执行此操作或与上述类似的方法?
无需代码生成来解决此问题:
static void run(String name, Runnable runnable) {
try {
runnable.run();
} catch (Throwable throwable) {
StackTraceElement[] stackTraceElements = throwable.getStackTrace();
StackTraceElement[] currentStackTrace = new Throwable().getStackTrace();
if (stackTraceElements != null && currentStackTrace != null) { // if disabled
int currentStackSize = currentStackStrace.length;
int currentFrame = stackTraceElements.length - currentStackSize - 1;
int methodIndex = name.lastIndexOf('.');
int argumentIndex = name.indexOf('(');
stackTraceElements[currentFrame] = new StackTraceElement(
name.substring(0, methodIndex),
name.substring(methodIndex + 1, argumentIndex),
null, // file name is optional
-1); // line number is optional
throwable.setStackTrace(stackTraceElements);
}
throw throwable;
}
}
Run Code Online (Sandbox Code Playgroud)
使用代码生成,您可以添加具有名称的方法,在方法中重新定义调用站点,展开框架并调用生成的方法,但这将更加有效,并且永远不会同样稳定.
这个策略在测试框架中是一种相当常见的方法,我们在Mockito和其他实用程序(如JRebel)中做了很多工作,通过重写异常堆栈帧来隐藏它们的魔力.
使用Java 9时,使用Stack Walker API进行此类操作会更有效.