在迭代地图时使用反射

时间:2013-11-09 01:58:06

标签: java reflection map iterator

我无法弄清楚如何使用反射来调用这个内部方法,这就是我想出的。但是,它不起作用:

interface Foo {
   void callMe();
} 

 public class Tester{

 public TreeMap<Integer, Foo> testMap = new TreeMap<Integer, Foo>();

 public void foo(Foo foo, Integer d) {
    testMap.put(d, foo);
}

 public void testCase() { 
    for (Integer key: testMap.keySet()) {
       testMap.get(key).callMe(d);   
    }
}

public static void main(String[] args) {

 Tester testUser = new tester();

 testUser.foo(new Foo(){ void callMe(Integer d){ 
   System.out.println("Test " + d); } 
  }, 5);

testUser.foo(new Foo(){ void callMe(Integer d){ 
   System.out.println("Test Two " + d); } 
  }, 10);

   testUser.testCase();

 }
}

我必须对代码进行哪些更改才能运行?

1 个答案:

答案 0 :(得分:1)

a)这不是反思

b)您应该使用testUser.foo(...)代替tester.foo(...)

相关问题