繁体   English   中英

字节好友-java.lang.NoSuchMethodException-正确的defineMethod语法是什么?

[英]Byte Buddy - java.lang.NoSuchMethodException - what is the correct defineMethod syntax?

我正在尝试使用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());
    }
}

此处的学习页面的访问字段部分中,声明了通过在定义方法后使用implementation ,然后使用FieldAccessor.ofBeanProperty()来创建设置器和获取器是很简单的

Method m = o.getClass().getDeclaredMethod("getId", int.class); 引发NoSuchMethodException。

创建getter和setter的正确语法是什么?

正确的方法调用应为

Method m = o.getClass().getDeclaredMethod("getId");

int是返回类型,您不必在getDeclaredMethod调用中指定返回类型-仅参数类型,而方法getId没有参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM