Byte Buddy - java.lang.NoSuchMethodException - what is the correct defineMethod syntax?

痴心易碎 提交于 2020-01-05 07:22:38

问题


I am trying to create a setter and a getter for a field using Byte Buddy.

public class Sample {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException {

        Class<?> type = new ByteBuddy()
                .subclass(Object.class)
                .name("domain")
                .defineField("id", int.class, Visibility.PRIVATE)               
                .defineMethod("getId", int.class, Visibility.PUBLIC).intercept(FieldAccessor.ofBeanProperty())
                .make()
                .load(Sample.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
                .getLoaded();

        Object o = type.newInstance();
        Field f = o.getClass().getDeclaredField("id");
        f.setAccessible(true);
        System.out.println(o.toString());       
        Method m = o.getClass().getDeclaredMethod("getId", int.class);
        System.out.println(m.getName());
    }
}

In the accessing field section of the learn pages here it is stated that creating a setter and getter is trivial by using an implementation after defining the method and then using FieldAccessor.ofBeanProperty()

The Method m = o.getClass().getDeclaredMethod("getId", int.class); throws the NoSuchMethodException.

What is the correct syntax for creating a getter and a setter?


回答1:


The correct method call should be

Method m = o.getClass().getDeclaredMethod("getId");

int is the return type, and you don't have to specify the return type in the getDeclaredMethod call - only the argument types and the method getId has no arguments.



来源:https://stackoverflow.com/questions/40692972/byte-buddy-java-lang-nosuchmethodexception-what-is-the-correct-definemethod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!