Raoul-Gabriel Urma、Mario Fusco 和 Alan Mycroft 在《Java 8 in Action》一书中指出:
public interface Adder{
int add(int a, int b);
}
public interface SmartAdder extends Adder{
int add(double a, double b);
}
Run Code Online (Sandbox Code Playgroud)
SmartAdder 不是函数式接口,因为它指定了两个称为 add 的抽象方法(一个是从 Adder 继承的)。
在书中的另一个类似示例中,以下接口称为功能接口。
public interface ActionListener extends EventListener {
void actionPerformed(ActionEvent e);
}
Run Code Online (Sandbox Code Playgroud)
与第二个示例相比,是什么让第一个示例不是功能接口?
我找到了以下代码,继承的 equals() 和 toString() 方法的用途是什么。
@FunctionalInterface
public interface FunInterface<T> {
// An abstract method declared in the functional interface
int test(T o1, T o2);
// Re-declaration of the equals() method in the Object class
boolean equals(Object obj);
String toString();
}
Run Code Online (Sandbox Code Playgroud) 我们有以下场景:
测试中,一些上下文变量需要更新。在测试中的确切位置以及确切应该发生的事情是可变的。我想提供一个“包装器”函数,它设置一些上下文变量,然后执行在函数调用中提供给它的所有断言。
因此,类似于以下内容:
public void withDefaultContextA(Function<???, Void> noArgsCall) {
setupDefaultContextA();
noArgsCall.invoke() // not sure how apply() would be invoked here
}
Run Code Online (Sandbox Code Playgroud)
或者:
public void withContextA(BiFunction<???, Context, Void> providedContextCall) {
setupContext(providedContext); // not sure how apply() would be invoked here
}
Run Code Online (Sandbox Code Playgroud)
在相应的测试中,这些应该被调用如下:
@Test
public void testSomething() {
withDefaultContextA(() -> {
... // do some asserts
}
withContext((new Context(...)) -> {
... // do some asserts
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?可以以这种方式使用 Java 8 函数吗?如果没有,还有另一种方法可以实现这一目标吗?
@FunctionalInterface
public interface ServiceCaller {
void callService();
}
//common method to execute any service call
public void executeService(ServiceCaller serviceCaller) {
//do common things
//i want to access dbValidationRequest/apiValidationRequest here for logging purpose
try {
serviceCaller.callService();
} catch (Exception ex) {
//do common things
LogUtils.log(logger, ex);
}
//do common things
}
//my clients call this
public void validateFromDb(DbValidationRequest dbValidationRequest){
commonUtils.executeService(()-> dbValidationService.validate(dbValidationRequest));
}
//my clients call this
public void validateFromApi(ApiValidationRequest apiValidationRequest){
commonUtils.executeService(()-> apiValidationService.validate(apiValidationRequest));
}
Run Code Online (Sandbox Code Playgroud)
这是Java Spring应用程序的控制器。在executeService方法中,我传递了ServiceCaller接口的一个实例。我使用此方法从控制器调用所有服务。如果我使用 intelliJ IDEA …
我想学习 Java 的“新”语法和 API 中的可能性。更新我的意思是 10+(比方说 10-13)。它主要围绕 lambdas 的声明和存储与映射中的值相同的签名的不同实现。最近我主要和 Gosu 一起工作,我可以用这个片段:
var longInput = 10000000L
new LinkedHashMap<String, block(long) : long>( {
"byte" -> (\x -> x as byte as long),
"short" -> (\x -> x as short as long),
"int" -> (\x -> x as int as long),
"long" -> (\x -> x as long as long)
}).eachKeyAndValue(\key, value ->
print("${longInput} ${value(longInput) == longInput ? "can" : "cannot"} be converted to ${key}")
)
Run Code Online (Sandbox Code Playgroud)
我可以在 Java 10 中类似地做到这一点:
import java.util.*;
public …Run Code Online (Sandbox Code Playgroud) 当使用下面的匿名类时,我们调用的变量x没有问题
interface Age {
int x = 21;
void getAge();
}
class AnonymousDemo {
public static void main(String[] args) {
Age oj1 = new Age() {
@Override
public void getAge() {
// printing age
System.out.print("Age is "+x);
}
};
oj1.getAge();
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我使用下面的 lambda 表达式相同的代码时,出现了异常:
interface Age {
int x = 21;
void getAge();
}
class AnonymousDemo {
public static void main(String[] args) {
Age oj1 = () -> { System.out.print("Age is "+x); };
oj1.getAge();
}
}
Run Code Online (Sandbox Code Playgroud)
这里会出现什么问题呢?知道lambda表达式只是实现匿名类的缩写。
根据功能接口的定义 -功能接口是仅包含一个抽象方法的接口。
但是Comparator<T>有两个抽象方法:
int compare(T o1, T o2);
boolean equals(Object obj);
Run Code Online (Sandbox Code Playgroud)
其他是默认和静态的。
JavaDocs 将其称为功能接口。怎么会这样?
我所看到的BiConsumer,BiPredicate,BiFunction但不能BiSupplier或类似。我尝试了下面的代码,但有一个异常说:
“在 BiSupplier 中发现的多个非覆盖抽象方法”。
@FunctionalInterface
public interface BiSupplier<T, R> {
/**
* Gets a first.
*
* @return a first
*/
T getFirst();
/**
* Gets a second.
*
* @return a second
*/
R getSecond();
}
Run Code Online (Sandbox Code Playgroud)
可以请一些人帮我解决这个问题。
我想了解Java的Consumer接口。我已经复制了。但是当我用匿名类定义替换 andThen() 方法的返回语句中的 lambda 表达式时,它会抛出 StackOverflowError :
interface Interface<T> {
void accept(T t);
default Interface<T> andThen(Interface<T> after) {
//return (T t)->{accept(t); after.accept(t);};//this runs correctly
//below is the anonymous class definition of above lambda expression
return new Interface<T>(){
@Override
public void accept(T t)
{
accept(t); //stackoverflow error thrown
after.accept(t);
}
};
}
}
//Main class:
public class Lambda2 {
public static void main(String args[]) {
Interface<String> e1=str -> System.out.println("in e1 - "+str);
Interface<String> e2=str -> System.out.println("in e2 - "+str);
Interface<String> e3 …Run Code Online (Sandbox Code Playgroud) 假设这个:
ExecutorService service = ...;
// somewhere in the code the executorService is used this way:
service.submit(() -> { ... });
Run Code Online (Sandbox Code Playgroud)
lambda表达式默认为Callable.
有没有办法让它实例化Runnable?
谢谢你的帮助.