我是 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)
我做错了什么?
最佳答案
java.util.Properties
延伸Hashtable<Object,Object>
.
因此,您必须将键和值转换为 String
为了调用你的方法(假设所有的键和值实际上是 String
s):
properties.forEach( (key, value) -> this.addOption((String) key, (String) value));
另一种方法是将方法的签名更改为:
public void addOption(Object key, Object value)
关于java - 使用 forEach() 时如何调用实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33777921/