问题
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