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没有参数。

更多相关文章

  1. Javascript 检查字符串是否是数字的几种方法
  2. 如何同时执行这些多方法调用?
  3. Java读取Unicode文件(UTF-8等)时碰到的BOM首字符问题,及处理方法
  4. java数组的拷贝四种方法:for、clone、System.arraycopy、arrays.c
  5. Spring Bean类可以包含静态方法吗?
  6. java 和 JavaScript都可以在创建一个对象时,就可以通过这个对象调
  7. 有什么方法可以避免HibernateOptimisticLockingFailureException
  8. Java:如何创建特定父类型的集合而不是其子类型?
  9. native方法的使用

随机推荐

  1. 对View DrawingCache的理解
  2. Android ListView+image的使用
  3. [Android] 代码实现按钮/图片自旋转(中心
  4. Andorid在布局文件中中文加粗
  5. (20120808)(01)android菜单与对话框--之日期
  6. android 获得屏幕宽度 高度
  7. 在AndroidManifest.xml文件中的android:w
  8. Widget动态换背景图片 android
  9. Android--通过关键字查找短消息数据库并
  10. android Activity单元测试