1
我正在尝试使用Byte Buddy为字段创建setter和getter。Byte Buddy - java.lang.NoSuchMethodException - 什么是正确的defineMethod语法?
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());
}
}
在学习页here的访问字段部分中指出,创建设定器和吸气剂是通过定义的方法,然后使用FieldAccessor.ofBeanProperty()
的Method m = o.getClass().getDeclaredMethod("getId", int.class);
抛出NoSuchMethodException后使用implementation
微不足道的。
什么是创建一个getter和setter正确的语法?