0

class のすべてのインスタンスには、 classAのインスタンスがありますB。メンバー変数に応じてA異なるメソッドを呼び出す必要があります。これは私が望むことを行う実装です:Bmethod_num

public class A {
    private B myB = new B();
    public int method_num = 1;
    public callBMethod() {
        if ( method_num == 1 )
            myB.method1();
        else
            myB.method2();
    }
}

public class B {
    public method1() { }
    public method2() { }
}

しかし、 を行う代わりに、どうにかして Bまたは直接myA.method_num = 1渡すことができるようにしたいと考えています。どうやってやるの?method1method2

4

5 に答える 5

3

次のようにリフレクションを使用できると思います

java.lang.reflect.Method method;
try {
  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
  // ...
} catch (NoSuchMethodException e) {
  // ...
}  

try {
  method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) {  //do proper handling
} catch (IllegalAccessException e) {//do proper handling
} catch (InvocationTargetException e) {//do proper handling
于 2013-09-10T11:53:39.713 に答える
0

Java リフレクション API は、メソッド タイプのオブジェクトをターゲット オブジェクトと一緒に渡し、メソッドをターゲット オブジェクトで呼び出す方法を提供します。

サンプルの例は次のとおりです。

Method m; // The method to be invoked

  Object target; // The object to invoke it on

  Object[] args; // The arguments to pass to the method

  // An empty array; used for methods with no arguments at all.
  static final Object[] nullargs = new Object[] {};

  /** This constructor creates a Command object for a no-arg method */
  public Command(Object target, Method m) {
    this(target, m, nullargs);
  }

  /**
   * This constructor creates a Command object for a method that takes the
   * specified array of arguments. Note that the parse() method provides
   * another way to create a Command object
   */
  public Command(Object target, Method m, Object[] args) {
    this.target = target;
    this.m = m;
    this.args = args;
  }

  /**
   * Invoke the Command by calling the method on its target, and passing the
   * arguments. See also actionPerformed() which does not throw the checked
   * exceptions that this method does.
   */
  public void invoke() throws IllegalAccessException,
      InvocationTargetException {
    m.invoke(target, args); // Use reflection to invoke the method
  }
于 2013-09-10T11:56:10.757 に答える