请看一下我的解决方案:
package com.example.demo;
public class LambdaDemo {
public static void main(String[] args) {
//doesn't compile
//LambdaRestrictedInterface x = () -> {};
LambdaRestrictedInterface y = new Test();
y.print();
}
private static class Test implements LambdaRestrictedInterface {
@Override
public void print() {
System.out.println("print");
}
}
public interface MyInterface {
void print();
}
public interface LambdaRestrictedInterface extends MyInterface {
@Override
default void print() {
//hack prevents lambda instantiating
}
}
}
想法是用默认的impl覆盖父接口
始发者编辑:经过深思熟虑,我决定接受此答案(因为它最适合我的需求,并且实施起来相当便宜),并且有一些正式的补充.实际上,已经意识到足以防止将接口用作lambda类型的最小手段就是在其抽象方法中添加默认实现.