What's the nearest substitute for a function p

2018-12-31 17:07发布

I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?

21条回答
宁负流年不负卿
2楼-- · 2018-12-31 17:55

One of the things I really miss when programming in Java is function callbacks. One situation where the need for these kept presenting itself was in recursively processing hierarchies where you want to perform some specific action for each item. Like walking a directory tree, or processing a data structure. The minimalist inside me hates having to define an interface and then an implementation for each specific case.

One day I found myself wondering why not? We have method pointers - the Method object. With optimizing JIT compilers, reflective invocation really doesn't carry a huge performance penalty anymore. And besides next to, say, copying a file from one location to another, the cost of the reflected method invocation pales into insignificance.

As I thought more about it, I realized that a callback in the OOP paradigm requires binding an object and a method together - enter the Callback object.

Check out my reflection based solution for Callbacks in Java. Free for any use.

查看更多
何处买醉
3楼-- · 2018-12-31 17:55

Check out lambdaj

http://code.google.com/p/lambdaj/

and in particular its new closure feature

http://code.google.com/p/lambdaj/wiki/Closures

and you will find a very readable way to define closure or function pointer without creating meaningless interface or use ugly inner classes

查看更多
春风洒进眼中
4楼-- · 2018-12-31 17:56

None of the Java 8 answers have given a full, cohesive example, so here it comes.

Declare the method that accepts the "function pointer" as follows:

void doCalculation(Function<Integer, String> calculation, int parameter) {
    final String result = calculation.apply(parameter);
}

Call it by providing the function with a lambda expression:

doCalculation((i) -> i.toString(), 2);
查看更多
登录 后发表回答