Sander_M Sander_M - 4 months ago 31
Java Question

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()
.defineField("id", int.class, Visibility.PRIVATE)
.defineMethod("getId", int.class, Visibility.PUBLIC).intercept(FieldAccessor.ofBeanProperty())
.load(Sample.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)

Object o = type.newInstance();
Field f = o.getClass().getDeclaredField("id");
Method m = o.getClass().getDeclaredMethod("getId", int.class);

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

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

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


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.