Sou*_*kar 28 java lambda java-8 functional-interface
在Java 8 中引入了lambda表达式以帮助减少样板代码.如果界面只有一个方法,它可以正常工作.如果它由多个方法组成,那么这些方法都不起作用.我该如何处理多种方法?
我们可以选择以下示例
public interface I1()
{
void show1();
void show2();
}
Run Code Online (Sandbox Code Playgroud)
那么主要功能的结构是什么来定义main本身的方法呢?
Yas*_*jaj 33
Lambda表达式仅可用于Eran所说的功能接口,但如果您确实需要接口中的多个方法,则可以将修饰符更改为default或static在必要时在实现它们的类中覆盖它们.
public class Test {
public static void main(String[] args) {
I1 i1 = () -> System.out.println(); // NOT LEGAL
I2 i2 = () -> System.out.println(); // TOTALLY LEGAL
I3 i3 = () -> System.out.println(); // TOTALLY LEGAL
}
}
interface I1 {
void show1();
void show2();
}
interface I2 {
void show1();
default void show2() {}
}
interface I3 {
void show1();
static void show2 () {}
}
Run Code Online (Sandbox Code Playgroud)
你不应该忘记继承的方法.
这里,I2继承show1并show2因此不能成为功能接口.
public class Test {
public static void main(String[] args) {
I1 i1 = () -> System.out.println(); // NOT LEGAL BUT WE SAW IT EARLIER
I2 i2 = () -> System.out.println(); // NOT LEGAL
}
}
interface I1 {
void show1();
void show2();
}
interface I2 extends I1 {
void show3();
}
Run Code Online (Sandbox Code Playgroud)
要确保您的界面是功能界面,您可以添加以下注释 @FunctionalInterface
@FunctionalInterface <------- COMPILATION ERROR : Invalid '@FunctionalInterface' annotation; I1 is not a functional interface
interface I1 {
void show1();
void show2();
}
@FunctionalInterface
interface I2 {
void show3();
}
Run Code Online (Sandbox Code Playgroud)
Era*_*ran 11
Lambda表达式只能用于实现功能接口,这些接口是具有单个抽象方法的接口.lambda表达式无法实现具有两个抽象方法的接口.
我通常直接在界面中创建一个静态工厂方法:
public inteface I1 {
void show1();
void show2();
public static I1 of(Runnable show1, Runnable show2) {
return new I1() {
void show1() { show1.run(); }
void show2() { show2.run(); }
};
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
I1 i1 = I1.of(() -> System.out.println("show1"), () -> System.out.println("show2"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7408 次 |
| 最近记录: |