サーバ管理者/開発者メモ書き・Linux、Windows等々

開発情報、サーバ管理・設定、モバイルなどの情報です。

過去の投稿日別表示

[ リスト | 詳細 ]

2012年2月4日

←2012年2月3日 | 2012年2月5日→

全1ページ

[1]

private メソッドの呼び出し リフレクション使用

当たり前の話しですが、privateメソッドは、他のクラスから呼べません。
しかし単体テストなどで、どうしても呼びたくなります。

以下、reflectionを使った参考。
テストする側のクラスには、
import java.lang.reflect.Method;
を使用します。


//テスト対象のクラス
public class HelloWorld {
//引数なし
private int pMethod() {
System.out.println("aa");
return 1;

}

//引数あり
private String pMethod1(String str1, String str2) {
System.out.println(str1 + " " + str2 );
return "private!";

}
}



//テストする側
import java.lang.reflect.Method;

テストクラス

public void test() throws Exception{

// クラス取得
Class<HelloWorld> c = HelloWorld.class;

// //引数なしのメソッドテスト
// // メソッド取得(メソッド名を文字列として指定)
// Method m = c.getDeclaredMethod("pMethod");
//
// // Privateメソッドの場合、以下の設定が必要
// m.setAccessible(true);
//
// Integer ret = (Integer) m.invoke(c.newInstance());
// System.out.println(ret);

// -----

// 引数の分、クラス型の配列を定義する。
Class[] args = { String.class, String.class };
Method m = c.getDeclaredMethod("pMethod1", args);
String str1 = "ABC, ZZZ";
String str2 = "9876543210";

m.setAccessible(true);

// 第二引数以降にメソッドに渡す引数をセット
String ret = (String) m.invoke(c.newInstance(), str1, str2);
System.out.println(ret);

} 

閉じる コメント(1)

閉じる トラックバック(0)

全1ページ

[1]


.

人気度

ヘルプ

Yahoo Image

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29
検索 検索
  今日 全体
訪問者 7 39316
ブログリンク 0 5
コメント 0 21
トラックバック 0 2

開設日: 2005/2/20(日)


プライバシーポリシー -  利用規約 -  ガイドライン -  順守事項 -  ヘルプ・お問い合わせ

Copyright (C) 2012 Yahoo Japan Corporation. All Rights Reserved.