【问题标题】:Using Reflection while iterating over a map迭代地图时使用反射
【发布时间】:2013-11-21 04:44:59
【问题描述】:

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

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();

 }
}

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

【问题讨论】:

    标签: java reflection map iterator


    【解决方案1】:

    a) 这不是反射

    b) 你应该使用testUser.foo(...) 而不是tester.foo(...)

    【讨论】:

    • 那是什么?我试图将接口传递给 TreeMap 的值并执行该接口的内部方法
    • 大概是一个回调对象。 (无论如何,流行语都被高估了。)
    • ...我在 b) 部分中提出的建议是主要的。其他一切看起来都不错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 2020-10-22
    • 2011-01-13
    • 1970-01-01
    • 2010-10-18
    • 2020-10-31
    相关资源
    最近更新 更多