Sander_M
Sander_M

Reputation: 1119

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

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?

Upvotes: 1

Views: 604

Answers (1)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

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.

Upvotes: 2

Related Questions