【问题标题】:bytebuddy with osgi container带有 osgi 容器的 bytebuddy
【发布时间】:2017-04-19 04:51:52
【问题描述】:

尝试编写一个简单的java代理,基于bytebuddy主页上的示例。我让代理工作,但是当我使用 OSGI 运行时运行它时,它会抛出 java.lang.NoClassDefFoundError。

任何指针?

java.lang.ClassNotFoundException: com.foo.javaagent.TimingInterceptor cannot be found by ..

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import java.lang.instrument.Instrumentation;


    public class TimerAgent {
        public static void premain(String arguments,
                                   Instrumentation instrumentation) {
            new AgentBuilder.Default()
                    .type(ElementMatchers.nameEndsWith("World"))
                    .transform((builder, type, classLoader, module) ->
                            builder.method(ElementMatchers.any())
                                    .intercept(MethodDelegation.to(TimingInterceptor.class))
                    ).installOn(instrumentation);
        }
    }

import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;

import java.lang.reflect.Method;
import java.util.concurrent.Callable;


public class TimingInterceptor {
    @RuntimeType
    public static Object intercept(@Origin Method method,
                                   @SuperCall Callable<?> callable) throws Exception {
        long start = System.currentTimeMillis();
        try {
            return callable.call();
        } finally {
            System.out.println(method + " took " + (System.currentTimeMillis() - start));
        }
    }
}

【问题讨论】:

    标签: java osgi javaagents byte-buddy


    【解决方案1】:

    TimingInterceptor 类被您的检测类引用,因此必须可见。 OSGi 通过类加载器隔离类,并且不将系统类加载器设置为加载代理的父级。为了避免这种情况,您需要将您的类注入到引导类加载器中,它们是普遍可见的。为此,请将您的拦截逻辑隔离在一个单独的 jar 中,并通过您用于安装代理的 Instrumentation 实例将此 jar 附加到引导类加载器搜索路径。您需要在安装代理之前这样做。

    【讨论】:

    • Rafael - 非常感谢您的快速回复。您编写了一个很棒的库。我能够让它工作。是否有关于如何修改 Method 输入参数、带有字节伙伴的 HTTP 拦截器的示例?
    猜你喜欢
    • 1970-01-01
    • 2012-05-02
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2016-04-12
    相关资源
    最近更新 更多