bytebuddy与osgi容器

时间:2017-04-19 04:51:52

标签: java osgi javaagents byte-buddy

尝试编写一个简单的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));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

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