2016-11-19 101 views
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正确的语法?

回答

2

正确的方法调用应该是

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

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

相关问题