2016-11-19 9 views
1

Byte Buddyを使用してフィールドのセッターとゲッターを作成しようとしています。学びページhereのアクセスフィールドセクションでByte Buddy - 正当な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()); 
    } 
} 

セッターとゲッターを作成する方法を定義し、その後Method m = o.getClass().getDeclaredMethod("getId", int.class);はないNoSuchMethodExceptionをスローFieldAccessor.ofBeanProperty()

を使用した後implementationを使用して、些細であることが述べられています。

getterとsetterを作成する正しい構文は何ですか?

答えて

2

正しいメソッド呼び出しが

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

intは、戻り値の型である必要があり、あなたはgetDeclaredMethod呼び出しで戻り値の型を指定する必要はありません - 唯一の引数の型と引数を持たないgetId方法を。

関連する問題