JavaでMethodUtils.invokeMethodを使用してメソッドをインジェクションする

JavaでMethodUtils.invokeMethodを使用してメソッドをインジェクションする

MethodUtils.invokeMethod()は、commons-beanutils-1.x.x.jarライブラリを使用すれば使えるようになります。

私の環境では、commons-beanutils-1.8.2.jarを使用しています。

だいたいの使い方は第一引数にthis、第二引数にメソッド名(String型)、第三引数に第二引数に設定したメソッドの引数を設定します。

以下、引数がない場合の例です。nullを設定します。

MethodUtils.invokeMethod(this, "method", null);

上記はmethod()メソッドを実行する例です。

以下、引数がある場合の例です。

MethodUtils.invokeMethod(this, "method", new Object[] { "aaa", 1.0 });

上記はmethod(String,double)メソッドを実行する例です。

以下のようにインジェクションした場合、method1実行完了後、method2が実行されます。

MethodUtils.invokeMethod(this, "method1", null);
MethodUtils.invokeMethod(this, "method2", new Object[] { "aaa", 1.0 });

以下、例です。

package jp.co.confrage;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.MethodUtils;

public class TestMain {

    /**
     * @param args
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     */
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Sample s = new Sample();
        s.start();
    }

    public static class Sample {
        public void start() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
            MethodUtils.invokeMethod(this, "method1", null);
            MethodUtils.invokeMethod(this, "method2", new Object[] { "aaa", 1.0 });
        }

        public void method1 () throws InterruptedException {
            Thread.sleep(10000);
            System.out.println("実行されました");
        }

        public void method2 (String str1, double str2) {
            System.out.println(str1);
            System.out.println(str2);
        }
    }
}

以下、実行結果です。

実行されました
aaa
1.0

コメント

タイトルとURLをコピーしました