gpt4 book ai didi

Java 8 构造方法引用

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:30 26 4
gpt4 key购买 nike

我正在阅读 Java 8 这本书,它附带了一个我重现的示例:

@FunctionalInterface
public interface Action {
public void perform();
}

实现者:

public final class ActionImpl implements Action {
public ActionImpl() {
System.out.println("constructor[ActionIMPL]");
}

@Override
public void perform() {
System.out.println("perform method is called..");
}
}

来电者:

public final class MethodReferences {

private final Action action;

public MethodReferences(Action action) {
this.action = action;
}

public void execute() {
System.out.println("execute->called");
action.perform();
System.out.println("execute->exist");
}

public static void main(String[] args) {
MethodReferences clazz = new MethodReferences(new ActionImpl());
clazz.execute();
}
}

如果调用此方法,则将以下内容打印到输出中:

constructor[ActionIMPL]
execute->called
perform method is called..
execute->exist

一切都很好,但是如果我使用方法引用,则不会打印 perform message 方法!这是为什么,我是不是漏掉了什么?

如果我使用这段代码:

MethodReferences clazz = new MethodReferences(() -> new ActionImpl());
clazz.execute();

或者这段代码:

final MethodReferences clazz = new MethodReferences(ActionImpl::new);

这是打印出来的:

execute->called
constructor[ActionIMPL]
execute->exist

没有异常消息或其他任何内容被打印出来。我正在使用 Java 8 1.8.25 64 位。

更新

对于像我一样正在学习的读者来说,这是正确的运行代码。

我创建了一个调用者类。

因为我需要实现一个空方法“从 Action 功能接口(interface)执行”,我需要将其作为参数传递给类构造函数 MethodReference 我引用了“MethodReferenceCall 的构造函数,它是一个空构造函数"我可以使用它。

public class MethodReferenceCall {
public MethodReferenceCall() {
System.out.println("MethodReferenceCall class constructor called");
}

public static void main(String[] args) {
MethodReferenceCall clazz = new MethodReferenceCall();
MethodReferences constructorCaller = new MethodReferences(MethodReferenceCall::new);
constructorCaller.execute();
}
}

最佳答案

这个

MethodReferences clazz = new MethodReferences(() -> new ActionImpl());

不使用方法引用,它使用 lambda 表达式。功能接口(interface)是Action

public void perform();

所以

() -> new ActionImpl()

被翻译成类似的东西

new Action() {
public void perform() {
new ActionImpl();
}
}

同样,在

MethodReferences clazz = new MethodReferences(ActionImpl::new);

确实使用构造函数引用的 ActionImpl::new 被翻译成类似的东西

new Action() {
public void perform() {
new ActionImpl();
}
}

ActionImpl::new 不会调用 new ActionImpl()。它解析为预期类型的​​实例,其功能接口(interface)方法实现为调用该构造函数。

关于Java 8 构造方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26497932/

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