Byte Buddy - java.lang.NoSuchMethodException - 什么是正确的defineMethod语法?
I am trying to create a setter and a getter for a field using Byte Buddy.
我正在尝试使用Byte Buddy为一个字段创建一个setter和一个getter。
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()
在学习页面的访问字段部分中,声明通过在定义方法之后使用实现然后使用FieldAccessor.ofBeanProperty()来创建setter和getter是微不足道的。
The Method m = o.getClass().getDeclaredMethod("getId", int.class);
throws the NoSuchMethodException.
方法m = o.getClass()。getDeclaredMethod(“getId”,int.class);抛出NoSuchMethodException。
What is the correct syntax for creating a getter and a setter?
创建getter和setter的正确语法是什么?
1 个解决方案
#1
2
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.
int是返回类型,您不必在getDeclaredMethod调用中指定返回类型 - 只有参数类型和方法getId没有参数。
更多相关文章
- Javascript 检查字符串是否是数字的几种方法
- 如何同时执行这些多方法调用?
- Java读取Unicode文件(UTF-8等)时碰到的BOM首字符问题,及处理方法
- java数组的拷贝四种方法:for、clone、System.arraycopy、arrays.c
- Spring Bean类可以包含静态方法吗?
- java 和 JavaScript都可以在创建一个对象时,就可以通过这个对象调
- 有什么方法可以避免HibernateOptimisticLockingFailureException
- Java:如何创建特定父类型的集合而不是其子类型?
- native方法的使用