首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Bytebuddy -截取java.lang.RuntimeException构造函数

Bytebuddy -截取java.lang.RuntimeException构造函数
EN

Stack Overflow用户
提问于 2020-04-17 19:24:04
回答 1查看 114关注 0票数 0

我正在尝试截取构造函数RuntimeException(String)。我正在尝试使用前面提到的here和显示的here中的Advice。而是onEnter(String message)onExit(String message)方法。我的检测类(在不同的jar中):

代码语言:javascript
运行
复制
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);
    }
}

}

它的名字是:

代码语言:javascript
运行
复制
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");
}

}

输出:

代码语言:javascript
运行
复制
[Instrumenting] starting to instrument 'java.lang.RuntimeException'
[Instrumenting] done

我做错了什么?

EN

回答 1

Stack Overflow用户

发布于 2020-04-18 03:14:54

当您的代理运行时,该类已经加载,而您没有指定例如RedefinitionStrategy.RETRANSFORM。因此,您的代理不会重新考虑已经装入的类。请注意,您应该设置一个比此更具体的忽略匹配器。

顺便说一下,通知是内联在目标类中的,不需要您的注入。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61270453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档