What is the closest thing Java has to the .NET Func<> and Action<> delegates?

落花浮王杯 提交于 2019-12-23 08:00:07

问题


Obviously, Java does not have delegates or functions as first class values and uses interfaces instead, but what is the closest interface to the Func<> or Action<> .NET delegates? There is Runnable and Callable<>, but only in flavors taking no parameters.

As Java cannot have overloaded types with the same name and different number of generic type arguments, I understand that there cannot be a single shared interface name, but there could be a Runnable1<>, Runnable2<> and so on.

Is this style of programming just not used in Java or am I missing any existing interfaces?


回答1:


I'm not very familiar with .Net, but from what I've seen so far it seems you would usually create an interface for each type of function/action you want to store. This is not really the same but sounds like what you're looking for.

(the interface is not anonymous, it has a name, a meaning and documentation, which might make code easier to read. On the other hand it is an extra hassle to have to write it, and you cannot just throw in any function that matches the signature).

Do you have a specific use case for which you're seeking a recommendation? It's hard to make generalized statements ;).




回答2:


I've created a jar for you, and for myself :)

maven info:

<dependency>
    <groupId>com.incarcloud</groupId>
    <artifactId>ac-func-tion</artifactId>
    <version>1.1.0</version>
</dependency>

then you can write code like c#

import com.incarcloud.lang.*;

Action<Integer> actFoo = (x)->{ System.out.println(x); }
actFoo.run(1024);

Func2<Integer, Integer, Integer> actAdd = (x,y)->{ return x+y; }
int sum = actAdd.call(5,6);

More information can be found here https://github.com/InCar/ac-func-tion



来源:https://stackoverflow.com/questions/7296606/what-is-the-closest-thing-java-has-to-the-net-func-and-action-delegates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!