小牛犊 发表于 2013-1-27 05:11:51

Reflection 反射续

1. 执行某对象的方法
public class MethodRun {public static void main(String[] args) throws Exception {Animal2 a = new Animal2();Class c = a.getClass();Class[] cc = new Class;// 執行這個方法需要的參數個數cc = int.class;// 跟方法的順序要一致cc = String.class;cc = 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");//因为这是静态方法,不需要借助实例运行。
   
页: [1]
查看完整版本: Reflection 反射续