gpt4 book ai didi

java - Supply接口(interface)中的get()在哪里实现?

转载 作者:行者123 更新时间:2023-12-01 07:44:34 24 4
gpt4 key购买 nike

我有这段代码

public <T> someMethod(Supplier<T> supplier) {
Objects.requireNonNull(supplier);
SupplierThrowsException<T, Throwable> supplierThrowsException = supplier::get;
return withThrowable(supplierThrowsException);
}

我这样调用它

obj.someMethod(() -> myMethod(message))

我 100% 确定 myMethod() 返回的对象的类没有实现供应商接口(interface)。那么get()的实现在哪里呢?

我浏览了 Javadoc,但没有得到任何结果。我想了解这里发生了什么事。

我找到了thisthis但这并不能消除我的疑问。如果我在这里遗漏了什么,请告诉我。

最佳答案

I am 100% sure that the class of the object returned by myMethod() does not implement Supplier interface.

当然可以,但是表达式 () -> myMethod(message) 可以。

请阅读15.27.4. Run-Time Evaluation of Lambda Expressions .

At run time, evaluation of a lambda expression is similar to evaluation of a class instance creation expression, insofar as normal completion produces a reference to an object. Evaluation of a lambda expression is distinct from execution of the lambda body.

Either a new instance of a class with the properties below is allocated and initialized, or an existing instance of a class with the properties below is referenced.

The value of a lambda expression is a reference to an instance of a class with the following properties:

  • The class implements the targeted functional interface type and, if the target type is an intersection type, every other interface type mentioned in the intersection.

简而言之,lambda 表达式 () -> myMethod(message) 将被解析为 Supplier 的实例。

Where is the implementation of get()?

您已在 lambda 主体中提供了它。

() -> myMethod(message) 

(它是一个语句表达式,是构造 lambda 主体的较短形式)

() -> {
return myMethod();
}

(它是一个值兼容的 block ,一个更扩展的版本,可以声明许多语句)

关于java - Supply接口(interface)中的get()在哪里实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55806969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com