3

別のクラス B のオブジェクトであるプライベート最終メンバー変数を持つクラス A があります。

Class A {
  private final classB obj;
}

Class B {
   public void methodSet(String some){
   }

}

クラス A が singleton であることは知っています。クラス B のメソッド「methodSet」を使用して値を設定する必要があります。classA にアクセスして、classA の ClassB のインスタンスにアクセスしようとします。

私はこれをします:

Field MapField = Class.forName("com.classA").getDeclaredField("obj");
MapField.setAccessible(true);
Class<?> instance = mapField.getType(); //get teh instance of Class B.
instance.getMethods()
//loop through all till the name matches with "methodSet"
m.invoke(instance, newValue);

ここで例外が発生します。

私はリフレクションが苦手です。誰かが解決策を提案したり、何が問題なのかを指摘したりできれば幸いです。

4

1 に答える 1

5

「リモート」リフレクションの意味がわかりません。リフレクションの場合でも、オブジェクトのインスタンスを手に持っている必要があります。

どこかで A のインスタンスを取得する必要があります。B のインスタンスについても同じことが言えます。

達成しようとしているものの実際の例を次に示します。

package reflection;

class  A {
     private final B obj = new B();
}


class B {
    public void methodSet(String some) {
        System.out.println("called with: " + some);
    }
}


public class ReflectionTest {
    public static void main(String[] args) throws Exception{
       // create an instance of A by reflection
       Class<?> aClass = Class.forName("reflection.A");
       A a = (A) aClass.newInstance();

       // obtain the reference to the data field of class A of type B
       Field bField = a.getClass().getDeclaredField("obj");
       bField.setAccessible(true);
       B b = (B) bField.get(a);

       // obtain the method of B (I've omitted the iteration for brevity)
       Method methodSetMethod = b.getClass().getDeclaredMethod("methodSet", String.class);
       // invoke the method by reflection
       methodSetMethod.invoke(b, "Some sample value");

}

}

お役に立てれば

于 2012-09-11T05:50:13.190 に答える