5.7 (2)反射举例

public class A {
  public void foo(String name) {
    System.out.println("Hello, " + name);
  }
}

可以编写另外一个类来反射调用A上的方法: 

import java.lang.reflect.Method;

public class TestClassLoad {
  public static void main(String[] args) throws Exception {
    Class<?> clz = Class.forName("A");
    Object o = clz.newInstance();
    Method m = clz.getMethod("foo", String.class);
    for (int i = 0; i < 16; i++) {
      m.invoke(o, Integer.toString(i));
    }
  }
}

posted @ 2017-03-07 14:27  motivated_Dou  阅读(139)  评论(0编辑  收藏  举报