Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

java - Byte-buddy delegating instance method to static method passing instance as a parameter

I wonder if using byte-buddy i can crate method in class

public class Foo {

  //some fields and getters 

  public String newMethod() {
    return FooPrinter.createCustomToString(this);
  }
}

so that it will invoke

public class FooPrinter() {
  public static String createCustomToString(Foo foo) {
     return foo.getSomeField() + " custom string";
  }
}

I have tried

builder
    .defineMethod("newMethod", String.class, Ownership.MEMBER, Visibility.PUBLIC)
    .intercept(MethodDelegation.to(FooPrinter.class))

and adding @This to parameter in FooPrinter but i receive exception that non of methods in FooPrinter allows for delegatrion from Foo.bar().

question from:https://stackoverflow.com/questions/66067155/byte-buddy-delegating-instance-method-to-static-method-passing-instance-as-a-par

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There must be something else to your setup, this works just as expected:

import net.bytebuddy.description.modifier.Ownership;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.This;

public class Sample {

    public static void main(String[] args) throws Exception {
        Foo instance = new ByteBuddy().subclass(Foo.class)
                .defineMethod("newMethod", String.class, Visibility.PUBLIC)
                .intercept(MethodDelegation.to(FooPrinter.class))
                .make()
                .load(Foo.class.getClassLoader())
                .getLoaded()
                .getConstructor()
                .newInstance();

        Object result = instance.getClass().getMethod("newMethod").invoke(instance);
        System.out.println(result);
    }

    public static class Foo {
        public String getSomeField() {
            return "someField";
        }
    }

    public static class FooPrinter {
        public static String createCustomToString(@This Foo foo) {
            return foo.getSomeField() + " custom string";
        }
    }
}

will print someField custom string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...