Javaのリフレクションメカニズム - 文字列の連結メソッド名メソッドを呼び出します

1つの パブリッククラス人{
 2      公共文字getPerson1(列I){
 3          リターン "PERSON1 - " + I。
4          
5      }
 6      パブリック文字getPerson2(列I){
 7          リターン "PERSON2 - " + I。
8          
9      }
 10      公共文字getPerson3(列I){
 11          リターン "Person3 - " + I。
12          
13      }
 14 }
コードの表示
1  @Test 
2      公共ボイドTEST7()はClassNotFoundExceptionが、ないInstantiationException、IllegalAccessExceptionが、ないNoSuchMethodExceptionは、SecurityException、はIllegalArgumentException、にInvocationTargetException {スロー
 3つの         
4          クラス<>個人= Class.forNameの( "com.Person")。
5          オブジェクトのnewInstance = Person.newInstance()。
6          INT iは=  1 ; I <  4 ; I ++ ){
 7              メソッドのメソッド=Person.getMethod( "getPerson" + I、String.class)。
8              文字列STR2 =(文字列)method.invoke(のnewInstance、新しいオブジェクト[] {I + ""})。
9              のSystem.out.println(STR2)。
10          }
 11      }
コードの表示
1 PERSON1 - 1 
2 PERSON2 - 2 
3 Person3 - 3

 

おすすめ

転載: www.cnblogs.com/jiaye77/p/11804269.html