[英]java 8 - store method in HashMap and get return value from method in map
I want to store methods pointer in map to execute them based on a string value. 我想将方法指针存储在map中,以便根据字符串值执行它们。 Аrom what I found, I can use
Map<String, Runnable>
to do it, but the problem is I want to get the return value from the method. 根据我的发现,我可以使用
Map<String, Runnable>
来完成它,但问题是我想从方法中获取返回值。
Say I have something like this: 说我有这样的事情:
private Map<String, Runnable> timeUnitsMap = new HashMap<String, Runnable>() {{
timeUnitsMap.put("minutes", () -> config.getMinutesValues());
}}
The method config.getMinutesValues()
is from another class. config.getMinutesValues()
方法来自另一个类。
How can I do int value = timeUnitsMap.get("minutes").run();
我该怎么做
int value = timeUnitsMap.get("minutes").run();
or to store something else in the map (instead of Runnable
) in order to get the value from the function in the map? 或者在地图中存储其他东西(而不是
Runnable
)以便从地图中的函数中获取值?
Runnable
doesn't return a value. Runnable
不返回值。 You should use Supplier
or Callable
instead. 您应该使用
Supplier
或Callable
。
The primary difference between Supplier
and Callable
is that Callable
allows you to throw a checked exception. Supplier
和Callable
之间的主要区别在于Callable
允许您抛出已检查的异常。 You then have to handle the possibility of that exception everywhere you use the Callable
. 然后,您必须在使用
Callable
任何地方处理该异常的可能性。 Supplier
is probably simpler for your use case. Supplier
可能更容易用于您的用例。
You would need to change your Map<String, Runnable>
to a Map<String, Supplier<Integer>>
. 您需要将
Map<String, Runnable>
更改为Map<String, Supplier<Integer>>
。 The lambda function itself wouldn't need changing. lambda函数本身不需要改变。
@assylias pointed out in a comment that you could also use Map<String, IntSupplier>
. @assylias在评论中指出你也可以使用
Map<String, IntSupplier>
。 Using an IntSupplier
avoids boxing your int
as an Integer
. 使用
IntSupplier
避免将int
IntSupplier
Integer
。
使用Callable而不是Runnable
。
You will need to use Callable instead of Runnable and also, you would need to override call() method. 您将需要使用Callable而不是Runnable,并且还需要覆盖call()方法。
You can get a clue from following snippet: 您可以从以下代码段获得线索:
private Map<String, Callable<Integer>> timeUnitsMap = new HashMap<String, Callable<Integer>>(){
{timeUnitsMap.put("minutes", () -> call());}};
and you would need to override call() method as well, 你还需要覆盖call()方法,
@Override
public Integer call() throws Exception {
return 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.