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!