Javaと情熱のあいだ

カステラとドーナツと珈琲

クラス名を指定して引数の有るインスタンスを簡単に生成する

commonsを使用して生成しても、書くコードが2,3行短くなるだけかも・・・。

材料は

org.apache.commons.beanutils

public class ConstructorUtilsExample {

    /**
     * 確認用文字列
     */
    private String hoge;

    /**
     *
     * コンストラクタ。
     */
    public ConstructorUtilsExample() {
    }

    /**
     *
     * 確認用コンストラクタ
     * @param hoge 確認用文字列
     */
    public ConstructorUtilsExample(final String hoge) {
        this.hoge = hoge;
    }

    /**
     *
     * 実行。
     * @throws Exception 例外
     */
    public void execute() throws Exception {

        final ConstructorUtilsExample cue =
            (ConstructorUtilsExample) ConstructorUtils.invokeConstructor(
                Class.forName(
                        "example.beanutils.ConstructorUtilsExample")
                        , new Object[]{"TEST"});

        System.out.println(cue.getHoge());
    }

    /**
     *
     * 確認用文字列を取得します。
     * @return 確認用文字列
     */
    public String getHoge() {
        return hoge;
    }

    /**
     *
     * 確認用文字列を設定します。
     * @param hoge 確認用文字列
     */
    public void setHoge(final String hoge) {
        this.hoge = hoge;
    }
}