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

How do I change the method name and keep the original method body #1612

Closed gzvincen closed 6 days ago

gzvincen commented 6 months ago

There are the following classes and code

public class Foo {
        public String bar(String arg) {
            return "bar: " + arg;
        }
    }

public static void main(String[] args) throws Exception {
        new ByteBuddy().rebase(Foo.class)
            .name(Foo.class.getPackageName() + ".Bar")
            .method(ElementMatchers.named("bar"))
            .intercept(SuperMethodCall.INSTANCE)
            .make()
            .saveIn(new File("Bar.class"));
    }

The generated class file is as follows:

public class Bar {
    public Bar() {
    }

    public String bar(String arg) {
        return this.bar$original$T45krq9n(arg);
    }
}

But I expect the generated class to look like this, where the bar method name is changed to barTest,Just by changing the method name, the body of the method remains the same. I have tried the method transform, there is no suitable method. Is there a proper way for me to just change the name of the method in the class?

public class Bar {
    public Bar() {
    }

    public String barTest(String arg) {
        return this.bar$original$T45krq9n(arg);
    }
}
raphw commented 6 months ago

Do you really need to change the method? I would change the modifier to private if so using ModifierTransformation and add another method with your desired name that invokes the now private method using MethodCall.