Byte Buddy - java.lang.NoSuchMethodException - wha

2019-08-01 05:59发布

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条回答
相关推荐>>
2楼-- · 2019-08-01 06:40

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.

查看更多
登录 后发表回答