1. 执行某对象的方法
public class MethodRun {
public static void main(String[] args) throws Exception {
Animal2 a = new Animal2();
Class c = a.getClass();
Class[] cc = new Class[3];// 執行這個方法需要的參數個數
cc[0] = int.class;// 跟方法的順序要一致
cc[1] = String.class;
cc[2] = String.class;
Method method1 = c.getMethod("eat", cc);
method1.invoke(a, 3, "猴子", "水果");// 执行a对象的eat这个方法
}
}
class Animal2 {
public void eat() {
System.out.println("动物吃东西");
}
public static void eat(int b, String a, String e) {
System.out.println(b + "只" + a + "吃" + e);
}
private void lasi() {
System.out.println("动物拉斯");
}
protected void run() {
System.out.println("动物跑");
}
}
运行结果:
3只猴子吃水果
2. 执行类的静态方法
method1.invake(null,3,''houzi","shuiguo");//因为这是静态方法,不需要借助实例运行。