采用lambda表达式:
import java.util.function.Function;
class Test {
public static void main(String... args) {
Function<Integer, Integer> increase = e -> e + 7; // lambda表达式
System.out.println(increase.getClass());
funcPlus(3, increase);
}
public static void funcPlus(int value, Function<Integer, Integer> func) {
System.out.println(func.apply(value));
}
}
输出结果:
class com.classTest.Test$$Lambda$1/0x0000000801200840
10
(1)apply() 函数在最新的1.8 Java版本才支持
java.util.function
Interface Function<T,R>
Type Parameters:
T - the type of the input to the function
R - the type of the result of the function
All Known Subinterfaces:
UnaryOperator<T>
Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
@FunctionalInterface
public interface Function<T,R>
Represents a function that accepts one argument and produces a result.
This is a functional interface whose functional method is apply(Object).
Since:
1.8
API文档:https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html
采用Callable方式:
import java.util.concurrent.Callable;
public class CallableUse {
public static void main(String... args) {
// final int num = 100770; or
int num = 100770;
// 使用匿名的内部类, 如果需要传递参数可能需要将变量转换成final:
try {
callMethod(100, new Callable<Integer>() {
public Integer call() {
return needOperation(num);
}
});
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public static int needOperation(int param) {
// do something
param = 999;
return param;
}
public static void callMethod(int i, Callable<Integer> myFunc) {
// do something
try {
System.out.println(myFunc.call() );
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出结果:
999
附:
同时在这篇帖子上有人采用Java反射机制:
https://stackoverflow.com/questions/4685563/how-to-pass-a-function-as-a-parameter-in-java
import java.lang.reflect.Method;
public class Demo {
public static void main(String[] args) throws Exception{
Class[] parameterTypes = new Class[1];
parameterTypes[0] = String.class;
Method method1 = Demo.class.getMethod("method1", parameterTypes);
Demo demo = new Demo();
demo.method2(demo, method1, "Hello World");
}
public void method1(String message) {
System.out.println(message);
}
public void method2(Object object, Method method, String message) throws Exception {
Object[] parameters = new Object[1];
parameters[0] = message;
method.invoke(object, parameters);
}
}
参考资料:
https://techndeck.com/how-to-pass-function-as-a-parameter-in-a-method-in-java-8/