我正在尝试截取构造函数RuntimeException(String)
。我正在尝试使用前面提到的here和显示的here中的Advice
。而是onEnter(String message)
或onExit(String message)
方法。我的检测类(在不同的jar中):
public class Instrumenting {
private static final String CLASS_NAME = "java.lang.RuntimeException";
public static void instrument(Instrumentation instrumentation) throws Exception {
System.out.println("[Instrumenting] starting to instrument '" + CLASS_NAME + "'");
instrumentation.appendToBootstrapClassLoaderSearch(new JarFile("C:\\Users\\Moritz\\Instrumenting\\dist\\Instrumenting.jar"));
File temp = Files.createTempDirectory("tmp").toFile();
ClassInjector.UsingInstrumentation.of(temp, ClassInjector.UsingInstrumentation.Target.BOOTSTRAP, instrumentation).inject(Collections.singletonMap(
new TypeDescription.ForLoadedType(RuntimeExceptionIntercept.class),
ClassFileLocator.ForClassLoader.read(RuntimeExceptionIntercept.class)));
new AgentBuilder.Default()
.ignore(ElementMatchers.none())
.with(new AgentBuilder.InjectionStrategy.UsingInstrumentation(instrumentation, temp))
.type(ElementMatchers.named(CLASS_NAME))
.transform((DynamicType.Builder<?> builder, TypeDescription td, ClassLoader cl, JavaModule jm) ->
builder
.visit(Advice.to(RuntimeExceptionIntercept.class)
.on(ElementMatchers.isConstructor())
)
).installOn(instrumentation);
System.out.println("[Instrumenting] done");
}
public static class RuntimeExceptionIntercept {
@Advice.OnMethodEnter
public static void onEnter(String message) throws Exception {
System.err.println("onEnter: " + message);
}
@Advice.OnMethodExit
public static void onExit(String message) throws Exception {
System.err.println("onExit: " + message);
}
}
}
它的名字是:
public class Main {
public static void premain(String agentArgs, Instrumentation instrumentation) throws Exception {
Instrumenting.instrument(instrumentation);
}
public static void main(String[] args) throws MalformedURLException, IOException {
new RuntimeException("message");
}
}
输出:
[Instrumenting] starting to instrument 'java.lang.RuntimeException'
[Instrumenting] done
我做错了什么?
发布于 2020-04-17 19:14:54
当您的代理运行时,该类已经加载,而您没有指定例如RedefinitionStrategy.RETRANSFORM
。因此,您的代理不会重新考虑已经装入的类。请注意,您应该设置一个比此更具体的忽略匹配器。
顺便说一下,通知是内联在目标类中的,不需要您的注入。
https://stackoverflow.com/questions/61270453
复制相似问题