Java反射メカニズムの小さな試み

1248 ワード

com.mycompany.reflect.Reflectクラス:
public class Reflect {
	public void showMeTheMoney(String money){
		System.out.println("give you "+money+" dollars!");
	}
}

このクラスのメソッドが呼び出されます.
 
com.mycompany.reflect.Mainクラス:
public class Main {

	/**
	 * @param args
	 */
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		try {
			Class<Reflect> clazz = (Class<Reflect>) Class.forName("com.mycompany.reflect.Reflect");
			Reflect r = clazz.newInstance();
			Method showMeTheMoney = clazz.getDeclaredMethod("showMeTheMoney", new Class[]{String.class});
			showMeTheMoney.invoke(r, "five");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
	}
}

 
実行結果は次のとおりです.
give you five dollars!