raphw / byte-buddy

Runtime code generation for the Java virtual machine.
https://bytebuddy.net
Apache License 2.0
6.23k stars 804 forks source link

Cannot resolve ambiguous delegation of public void java.lang.Thread.run() to public final native void java.lang.Object.notify() or public final native void java.lang.Object.notifyAll() #1555

Closed tutuerhao closed 11 months ago

tutuerhao commented 11 months ago

Cannot resolve ambiguous delegation of public void java.lang.Thread.run() to public final native void java.lang.Object.notify() or public final native void java.lang.Object.notifyAll()

public static void main(String[] args) throws IOException {
        ByteBuddyAgent.install();

        Map<TypeDescription, byte[]> map = new HashMap<>();
        map.put(TypeDescription.ForLoadedType.of(TraceThreadIntercepter.class), ClassFileLocator.ForClassLoader.read(TraceThreadIntercepter.class));
        map.put(TypeDescription.ForLoadedType.of(Object.class), ClassFileLocator.ForClassLoader.read(Object.class));
        ClassInjector.UsingUnsafe.ofBootLoader().inject(map);
        Thread t = new Thread(() -> System.out.println("Thread run"));
        new ByteBuddy().redefine(Thread.class)
                .method(ElementMatchers.named("run"))
                .intercept(MethodDelegation.to(new TraceThreadIntercepter()))
                .make()
                .load(Thread.currentThread().getContextClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
        t.start();
    }

    public static class TraceThreadIntercepter {

        @RuntimeType
        public void run(@SuperCall Callable zuper) {
            System.err.println("Trace start");
            try {
                zuper.call();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            System.err.println("Trace end");
        }
    }
raphw commented 11 months ago

With redefinition, you replace methods and no super method might be available. That's why it considers different delegation targets then your method.

Have a look into Advice which is likely better suited.

tutuerhao commented 11 months ago

Could you please give an example? @raphw

raphw commented 11 months ago

It would work without @SuperCall Callable zuper. But if you wanted to add code to the beginning and end of a method, Advice does exactly that. Have a look at the javadoc for the class.

tutuerhao commented 11 months ago

Thanks! @raphw

tutuerhao commented 11 months ago

Thanks! @raphw