1

ここで少し助けが必要です。私の問題を解決する方法があれば教えてください。

私がこのクラスを持っているとしましょう:

public testClass{

    public int example1(){
    return 2;
    }
    public int example2(){
    return 0;
    }
    public int example3(){
    return 456;
    }
}

この方法と同じことを動的に行う方法が必要です

public int methodeSwitch(int a){
   if (a==1){return method1;}
   if (a==2){return method2;}
   if (a==3){return method3;}
   return null;
}

私の問題は、50以上のフィールドを持つ巨大なクラス(dto)があることです。そのため、現在使用しているフィールドに応じて、ゲッターとセッターを使用したいと思います(そう、動的に)。(java.lang.Field、wouuuを使用して)フィールドにアクセスする方法は知っていますが、(動的に作成される)名前でメソッドをキャストする方法がわかりません。

ヒントを教えてくれるだけでも素晴らしいです!

ありがとうFabien

編集:明確にするために、私は基本的に私のクラスのすべてのセッターを使用するメソッドを書かなければならないので、私が次のようなものを使用できる場合

useMethod("set"+fields[i]+"();");

これは役に立ち、数十行のコードを書くのを防ぐことができます。

助けてくれてありがとう!;)

4

3 に答える 3

2

クラスから宣言されたメソッドを取得するには、リフレクションを使用する必要があります。これらのメソッドは、ゲッター/セッターを呼び出すクラスに存在し、それfieldsString[]フィールド名であると想定しています。

private Object callGet(final String fieldName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    final Method method = getClass().getDeclaredMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));
    return method.invoke(this, (Object[]) null);
}

private void callSet(final String fieldName, final Object valueToSet) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    final Method method = getClass().getDeclaredMethod("set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), new Class[]{valueToSet.getClass()});
    method.invoke(this, new Object[]{valueToSet});
}

これを正確に行うために設計されたライブラリであるCommonsBeansUtilもご覧ください...

于 2013-03-05T15:58:34.630 に答える
0

リフレクションAPIとMethod.invoke:を使用できます

http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke%28java.lang.Object,%20java.lang.Object...%29

イベントは、それを行うのは良い習慣ではないと確信していますが。

于 2013-03-05T15:51:34.357 に答える
0

リフレクションを使用して、このようなことを試すことができます。

public int methodeSwitch(int a)  {
    Map<Integer,String> methods = new HashMap<Integer,String>();
    methods.put(1, "example1");
    methods.put(2, "example2");
    methods.put(3, "example3");

    java.lang.reflect.Method method;
    try {
        method = this.getClass().getMethod(methods.get(a));
        return (Integer) method.invoke(this);
    } catch(Exception ex){//lots of exception to catch}
    return 0;
}

これは概念実証にすぎません。もちろん、動的メソッドを別の場所で初期化し(静的初期化)、methods.get(a)有効範囲内にないかどうかを確認する必要があります。

于 2013-03-05T16:00:49.477 に答える