** 任意のクラスのインスタンスを動的に生成し、実行する [#u345bd7a]

 package example;
 
 public class TestClass {
 
 	public String getMessage(String userName){
 		return "こんにちわ!" + userName + "さん";
 	}
 }

 package example;
 
 import java.lang.reflect.Method;
 
 public class makeInstance {
 
 	public static void main (String[] args){
 		
 		String targetClassName  = "example.TestClass";
 		String targetMethodName = "getMessage";
 		
 		try {
 			Class c = Class.forName(targetClassName);
 			Object service = (Object)c.newInstance();
 			Class[] classArgs = new Class[]{String.class};
 			Method mthod = Class.forName(targetClassName).getMethod(targetMethodName, classArgs);
 			Object[] obj = new Object[]{"ゲスト"};
 			Object res = mthod.invoke(service, obj);
 			System.out.println("【"+targetClassName+targetMethodName+"の実行結果】");
 			System.out.println("  " + res.toString());
 		} catch (Exception e){
 		}
 	}
 }

 -- 実行結果 --
 【example.TestClassgetMessageの実行結果】
   こんにちわ!ゲストさん


トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS