【问题标题】:How to call an instance method when using forEach()使用forEach()时如何调用实例方法
【发布时间】:2015-11-18 10:44:33
【问题描述】:

我是 Java 新手,我想为 Properties 对象中的每个键值对调用成员函数,如下所示:

public void addOption(String key, String value)
{
    // ...
}

public void foo()
{
    Properties properties = new Properties();
    // reads the property list from the input byte stream
    ...

    properties.forEach( (key, value) -> this.addOption(key, value));  // compiler error
    properties.forEach( (key, value) -> System.out.println("Key: " + key + ": Value: " + value));   // OK
}

报如下编译错误:

The method addOption(String, String) in the type Configuration is not applicable for the arguments (Object, Object)

我做错了什么?

【问题讨论】:

  • key 是什么类型?向我们展示定义
  • 看来你的keyvalueObject 类型,所以只需键入它并尝试。
  • @RossDrew 我已经添加了定义。键和值是Strings。

标签: java foreach lambda


【解决方案1】:

java.util.Properties 扩展Hashtable<Object,Object>

因此,您必须将键和值转换为 String 才能调用您的方法(假设所有键和值实际上都是 Strings):

properties.forEach( (key, value) -> this.addOption((String) key, (String) value));

另一种方法是将方法的签名更改为:

public void addOption(Object key, Object value)

【讨论】:

    【解决方案2】:

    您应该将keyvalue 转换为String

       properties.forEach( (key, value) -> this.addOption((String)key, (String) value));
    

    为什么不使用Map<String,String> 来获得Generic 的优势

    【讨论】:

    • 您能详细说明一下吗?我的理解是属性类型不是通用的。
    猜你喜欢
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多