public class Test {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("老写法");
}
});
new Thread(() -> {
System.out.println("函数式接口新写法");
});
}
}
为什么可以这么写?
public class Test {
public static void main(String[] args) {
new Thread(()->{
System.out.println("songxianyang");
});
}
}
答: 函数式接口
先说一个注解@FunctionalInterface
-
用的信息注释类型,以指示在接口类型声明旨在是一个功能接口由Java语言规范所定义的。 在概念上,功能界面只有一个抽象方法。如果接口声明了一个抽象方法覆盖的公共方法之一java.lang.Object ,也不会向接口的抽象方法计数统计以来的接口的任何实施都会有一个实现从java.lang.Object或其他地方。
请注意,可以使用lambda表达式,方法引用或构造函数引用创建函数接口的实例。
如果使用此注释类型注释类型,则编译器需要生成错误消息,除非:
- 类型是接口类型,而不是注释类型,枚举或类。
- 注释类型满足功能界面的要求。
new Runnable();无参无返回型函数,没有参数也没有返回值 new Function(); 供给型函数,有参有返回型函数。 new Consumer(); 消费型函数,一个参数,没有返回值 new Supplier(); 供给型函数,有参有返回型函数。底层源码 Runnable
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
Function
@FunctionalInterface public interface FunctionConsumer{ R apply(T t); default Function compose(Function super V, ? extends T> before) { Objects.requireNonNull(before); return (V v) -> apply(before.apply(v)); } default Function andThen(Function super R, ? extends V> after) { Objects.requireNonNull(after); return (T t) -> after.apply(apply(t)); } static Function identity() { return t -> t; } }
@FunctionalInterface public interface ConsumerSupplier{ void accept(T t); default Consumer andThen(Consumer super T> after) { Objects.requireNonNull(after); return (T t) -> { accept(t); after.accept(t); }; } }
@FunctionalInterface public interface Supplier代码实现{ T get(); }
- 需求:简化if…else{} 可以采用
package com.example.demo.myfunction.impl;
import com.example.demo.myfunction.ExceptionFunction;
import com.example.demo.myfunction.FunctionIfEOrElse;
public final class MyUtils {
public static FunctionIfEOrElse isTrue(Boolean b) {
return (runnableTrue, runnableFalse) -> {
if (b) {
runnableTrue.run();
} else {
runnableFalse.run();
}
};
}
public static ExceptionFunction isMsg() {
return msg1 -> {
System.out.println(msg1);
};
}
}
ExceptionFunction
@FunctionalInterface
public interface ExceptionFunction {
void throwOut(String msg);
}
FunctionIfEOrElse
@FunctionalInterface
public interface FunctionIfEOrElse {
void print(Runnable runnableTrue,Runnable runnableFalse);
}
测试类
public class PrintTest {
public static void main(String[] args) {
MyUtils.isTrue(true).print(() -> {
System.out.println("执行true业务代码");
}, () -> {
System.out.println("执行FALSE业务代码");
});
RuntimeException exception = new RuntimeException("我报错了 请指示");
MyUtils.isMsg().throwOut(exception.getMessage());
}
总结
- Function函数可以大大的简化代码。看着就是优雅好懂
Java8新特性之lambda与stream-骚操作



