我在阅读一个我正在尝试掌握的框架的源代码时,发现了Java 8的新语法:
Runtime.getRuntime().addShutdownHook(new Thread(Sirius::stop));
在Clojure中,我可以将其翻译为:
(.addShutdownHook (Runtime/getRuntime) (Thread. ????))
但我不确定???
应该填什么。
IFn扩展了Runnable接口,因此你只需要执行:
#(Sirius/stop)
Java 8函数式接口在底层通过实现仅有一个方法的接口来创建匿名实现。所以
new Thread(Sirius::stop)
只是语法糖而已。
new Thread(new Runnable {
public void run() {
Sirius.stop();
}
})
@george-simms的解释是正确的,但对于那些寻找不是Runnable
/Callable
示例并需要使用reify
的人,这里有一个例子。
假设您想要像这样使用DateTimeFormatter
parse
方法:
DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE();
LocalDate d = dtf.parse("2019-04-04", LocalDate::from);
您需要检查parse
的第二个参数的功能接口类型,我们的情况下是TemporalQuery
。这意味着您需要实例化
TemporalQuery
并实现其唯一方法(功能接口始终只有一个方法),以便调用LocalDate
类上的静态方法from
。因此,在Clojure中它也会被翻译成:
(import 'java.time.format.DateTimeFormatter)
(import 'java.time.temporal.TemporalQuery)
(import 'java.time.LocalDate)
(let [dtf (DateTimeFormatter/ISO_LOCAL_DATE)]
(.parse dtf "2019-04-04"
(reify TemporalQuery
(queryFrom [this temporal]
(LocalDate/from temporal)))))
(Thread. #(Sirius/stop))
应该可以工作,它只是一个静态方法。 - noisesmithThread.start()
时)。 - Mark Rotteveel