字节好友-java.lang.NoSuchMethodException-正确的defineMethod语法是什么? [英] Byte Buddy - java.lang.NoSuchMethodException - what is the correct defineMethod syntax?
问题描述
我正在尝试使用Byte Buddy为字段创建一个setter和getter。
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());
}
}
在学习页面的访问字段部分在此指出,使用实现创建一个setter和getter很简单 code>定义方法后,然后使用
FieldAccessor.ofBeanProperty()
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()
Method m = o.getClass()。getDeclaredMethod( getId,int.class);
引发NoSuchMethodException。
The Method m = o.getClass().getDeclaredMethod("getId", int.class);
throws the NoSuchMethodException.
什么是
推荐答案
正确的方法调用应该是
Method m = o.getClass().getDeclaredMethod("getId");
int
是返回类型,而您不必在 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.
这篇关于字节好友-java.lang.NoSuchMethodException-正确的defineMethod语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!