简体   繁体   English

bytebuddy与osgi容器

[英]bytebuddy with osgi container

Trying to write a simple java agent, based on the sample on bytebuddy homepage. 尝试编写一个简单的java代理,基于bytebuddy主页上的示例。 I got the agent working, but when I run it with OSGI run time, it throws java.lang.NoClassDefFoundError. 我让代理工作,但是当我用OSGI运行时运行它时,它会抛出java.lang.NoClassDefFoundError。

Any pointers ? 有什么指针吗?

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));
        }
    }
}

The TimingInterceptor class is referenced by your instrumented classes and must therefore be visible. TimingInterceptor类由检测类引用,因此必须可见。 OSGi isolates classes by their class loaders and does not set the system class loader as a parent where the agent is loaded. OSGi通过类加载器隔离类,并且不将系统类加载器设置为加载代理的父类。 To circumvent this, you need to inject your classes into the bootstrap class loader where they are universially visible. 为了避免这种情况,您需要将类注入引导类加载器,它们在这些类加载器中是普遍可见的。 To do so, isolate your interception logic in a seperate jar and attach this jar to the bootstrap class loader search path via the Instrumentation instance you use for installing the agent. 为此,请将隔离逻辑隔离在单独的jar中,并通过用于安装代理的Instrumentation实例将此jar附加到bootstrap类加载器搜索路径。 You need to do so before installing the agent. 您需要在安装代理之前执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM