使用字节好友的Advice时,抛出java.lang.NoClassDefFoundError的Exception



由于某种原因,我一直在分析我自己的旧jar文件(不幸的是,源代码已经丢失(。我知道我要找到什么部分,但记不起它在哪里了。所以决定使用bytebuddy来获取jar文件的所有运行流。记录所有类(除了库类,例如java.lang.*(中所有方法的参数值和返回值就足够了。我尝试了一些修改后的示例代码,但有一个例外:

public static void premain(final String agentArgs,
final Instrumentation inst) {
System.out.println(
"+++Hey, look: I'm instrumenting a freshly started JVM!");
new AgentBuilder.Default()
.type(ElementMatchers.any())
.transform(new MetricsTransformer())
.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
.with(AgentBuilder.TypeStrategy.Default.REDEFINE)
.installOn(inst);
}
private static class MetricsTransformer implements AgentBuilder.Transformer {
@Override
public DynamicType.Builder<?> transform(
final DynamicType.Builder<?> builder,
final TypeDescription typeDescription,
final ClassLoader classLoader,
final JavaModule module) {
final AsmVisitorWrapper methodsVisitor =
Advice.to(EnterAdvice.class, ExitAdviceMethods.class)
.on(ElementMatchers.isAnnotatedWith(CollectMetrics.class)
.and(ElementMatchers.isMethod()));
final AsmVisitorWrapper constructorsVisitor =
Advice.to(EnterAdvice.class, ExitAdviceConstructors.class)
.on(ElementMatchers.isAnnotatedWith(CollectMetrics.class)
.and(ElementMatchers.isConstructor()));
return builder.visit(methodsVisitor).visit(constructorsVisitor);
}
private static class EnterAdvice {
@Advice.OnMethodEnter
static long enter() {
return System.nanoTime();
}
}
private static class ExitAdviceMethods {
@Advice.OnMethodExit(onThrowable = Throwable.class)
static void exit(@Advice.Origin final Executable executable,
@Advice.Enter final long startTime,
@Advice.Thrown final Throwable throwable) {
final long duration = System.nanoTime() - startTime;
System.out.println(duration);;
}
}
}

byte buddy的版本是1.9.5、1.7.11jdk版本:1.8.0.191

和cmd:中的异常

E:>cd E:workshop_android_studioBounAgentoutartifactsBounAgent_jar
E:BounAgent_jar>java -javaagent:BounAgent.jar -jar untitled.jar
Exception in thread "main" java.lang.NoClassDefFoundError: net/bytebuddy/matcher
/ElementMatcher
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.getDeclaredMethod(Unknown Source)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(Unknown Sou
rce)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(Unknown So
urce)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.matcher.ElementMatche
r
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 5 more

本机方法中的致命错误:处理-javaagent失败的

提前谢谢。

根据我发现的一篇文章:

要启动代理,必须将代理类和资源捆绑在一个jar中,并在jar清单中将agent Class属性设置为包含premain方法的代理类的名称。(代理必须始终绑定为jar文件,不能以分解格式指定。(

您的代理JAR文件("BounAgent.JAR"(似乎没有以正确的形式包含所有依赖项。特别是,bytebuddy类不在JAR文件中。这导致代理类无法加载。

最新更新