我正在尝试使用 Byte Buddy 拦截构造函数调用,这是我的示例代码:
package t;
import static net.bytebuddy.dynamic.loading.ClassLoadingStrategy.Default.INJECTION;
import static net.bytebuddy.implementation.MethodDelegation.to;
import static net.bytebuddy.matcher.ElementMatchers.any;
import java.util.concurrent.Callable;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
public class Bar {
public static void main (String[] args) {
new ByteBuddy ().subclass (Object.class)
.name ("t.Foo").constructor (any ()).intercept (to (new Object () {
@RuntimeType
public Object construct (@SuperCall Callable<Object> z) throws Exception {
System.out.println ("CALLING XTOR");
return z.call ();
}
})).make ().load (Bar.class.getClassLoader (), INJECTION).getLoaded ();
}
}
这会产生以下异常:
Exception in thread "main" java.lang.IllegalStateException: Error invoking java.lang.ClassLoader#findClass
at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Resolved.loadClass(ClassInjector.java:392)
at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.inject(ClassInjector.java:201)
at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default$InjectionDispatcher.load(ClassLoadingStrategy.java:199)
at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default.load(ClassLoadingStrategy.java:114)
at net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:3302)
at t.Bar.main(Bar.java:21)
Caused by: java.lang.ClassFormatError: Bad method name at constant pool index 19 in class file t/Foo$auxiliary$EalKkAhD
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Resolved.loadClass(ClassInjector.java:388)
... 5 more
我看到了这个相关的问题,但我确实得到了一个碰撞异常(好像构造函数被定义了两次)。