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!

评论
发表评论

您还没有登录,请登录后发表评论

chxkyy
搜索本博客
我的相册
64b3c62f-d494-3858-811a-32af005a64cb-thumb
ie7
共 2 张
最近加入圈子
存档
最新评论