chi*_*tiz 7 java java-8 method-reference constructor-reference
我正在阅读perform message它附带的样本我重现..
@FunctionalInterface
public interface Action {
public void perform();
}
Run Code Online (Sandbox Code Playgroud)
实施者
public final class ActionImpl implements Action {
public ActionImpl() {
System.out.println("constructor[ActionIMPL]");
}
@Override
public void perform() {
System.out.println("perform method is called..");
}
}
Run Code Online (Sandbox Code Playgroud)
来电者.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果调用此方法则将以下内容打印到输出中
constructor[ActionIMPL]
execute->called
perform method is called..
execute->exist
Run Code Online (Sandbox Code Playgroud)
一切都很好,但如果我使用方法参考不MethodReference打印方法!为什么我错过了什么?
如果我使用此代码
MethodReferences clazz = new MethodReferences(() -> new ActionImpl());
clazz.execute();
Run Code Online (Sandbox Code Playgroud)
或者这个代码
final MethodReferences clazz = new MethodReferences(ActionImpl::new);
Run Code Online (Sandbox Code Playgroud)
打印出来
execute->called
constructor[ActionIMPL]
execute->exist
Run Code Online (Sandbox Code Playgroud)
perform message
任何帮助都非常感谢我使用
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();
}
}
Run Code Online (Sandbox Code Playgroud)
更新
对于像我这样学习的人来说,这是正确运行的代码.
我创建了一个调用者类.
因为我需要实现一个空方法MethodReference,我需要作为参数传递给类构造函数perform message我引用的构造函数MethodReference
@FunctionalInterface
public interface Action {
public void perform();
}
Run Code Online (Sandbox Code Playgroud)
我希望能帮助委内瑞拉人提出最好的问候.
Sot*_*lis 11
这个
MethodReferences clazz = new MethodReferences(() -> new ActionImpl());
Run Code Online (Sandbox Code Playgroud)
不使用方法引用,它使用lambda表达式.所述功能接口Action的
public void perform();
Run Code Online (Sandbox Code Playgroud)
所以
() -> new ActionImpl()
Run Code Online (Sandbox Code Playgroud)
被翻译成类似的东西
new Action() {
public void perform() {
new ActionImpl();
}
}
Run Code Online (Sandbox Code Playgroud)
同样地,在
MethodReferences clazz = new MethodReferences(ActionImpl::new);
Run Code Online (Sandbox Code Playgroud)
该
new Action() {
public void perform() {
new ActionImpl();
}
}
Run Code Online (Sandbox Code Playgroud)
它使用构造函数引用,被翻译成类似的东西
MethodReferences clazz = new MethodReferences(() -> new ActionImpl());
Run Code Online (Sandbox Code Playgroud)
这ActionImpl::new不会调用ActionImpl::new.它解析为期望类型的实例,其功能接口方法实现为调用该构造函数.
| 归档时间: |
|
| 查看次数: |
5372 次 |
| 最近记录: |