JDK中是否有标准的功能接口,什么都不带,什么都不返回?我找不到一个.类似于以下内容:
@FunctionalInterface
interface Action {
void execute();
}
Run Code Online (Sandbox Code Playgroud) 什么是一个方法的Java 8功能接口什么都不带,什么都不返回?
即,相当于Action
带void
返回类型的C#参数?
我有一个通用的私有方法,它执行常见的任务,并由其他方法使用.通用方法if
和else
条件,支持被调用的其他方法.例:
private void myGenericMethod(String name, int age){
common task1;
common task2;
if(name!= null && name.length > 0){
specific task 1;
specific task 2;
} else{
specific task 3;
specific task 4;
}
if(age > 18){
specific task 1`;
specific task 2`;
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用Java 8 lambda,我创建了一个Invoker
用invoke
方法调用的函数接口.
public interface Invoker{
public void invoke()
}
Run Code Online (Sandbox Code Playgroud)
现在我的泛型方法看起来像这样,公共方法适当地处理调用函数回调:
private void myGenericMethod(Invoker invoker){
common task1;
common task2;
invoker.invoke();
}
Run Code Online (Sandbox Code Playgroud)
我可以使用JDK中的功能接口而不是自己创建这个接口吗?
为了减少JPA中每个属性更新的代码重复,我想将函数指针交给doTransaction
并调用该函数.我怎么能在Java 8中做到这一点?
public void modifySalary(Person person, float salary) {
doTransaction(person.setSalary(salary));
}
public void doTransaction(final Function<Void, Void> func) {
em.getTransaction().begin();
func.apply(null);
em.getTransaction().commit();
}
Run Code Online (Sandbox Code Playgroud) 所以我连续20个二传手,所有这些都可能会失败.如果一个失败或者用try catch包围它们而不是跳过它们,那么有没有办法用Java 8s的一些功能做到这一点?
例如,我在想这样的事情:
public void mapElement(Function function) {
try the function
catch if something goes wrong
}
Run Code Online (Sandbox Code Playgroud)
然后我可以像这样使用它:
mapElement(myObject.putA(a));
mapElement(myObject.putB(b));
mapElement(myObject.putC(c));
....
Run Code Online (Sandbox Code Playgroud) 最近,我想知道Runnable经常在功能上下文中使用。同时,根据javadoc,它的语义非常接近多线程,但在这种情况下并没有使用它:
Runnable接口应该由实例打算由线程执行的任何类实现。该类必须定义一个没有参数的方法,称为run。该接口旨在为希望在活动状态下执行代码的对象提供通用协议。例如,Runnable由Thread类实现。处于活动状态仅表示线程已启动但尚未停止。
是Runnable
相当于Supplier<Void>
?或Runnable
等同于Function<Void,Void>
,为什么不是供应商呢?Runnable如何与已经提供的功能接口的java.util.function包对齐。