是否有Java中的Objective-C块之类的东西? [英] Is there anything like an Objective-C block in Java?
问题描述
我只是在学习Java,并且之前我已经在Objective-C中开发了应用程序.我喜欢块"的概念,因为它们允许代码在发生某些事情后运行.
I'm just learning Java, and I've developed apps in Objective-C before. I like the concept of "blocks", because they allow code to be ran after something happens.
例如,要在SpriteKit应用程序中经过一定时间后执行一个块,该应用程序会从场景myScene
调用方法helloWorld
:
For example, to execute a block after a certain amount of time in a SpriteKit app that calls a method helloWorld
from scene myScene
:
[myScene runAction:[SKAction sequence:@[[SKAction waitForDuration:5], [SKAction runBlock:^{
[myScene helloWorld];
}]]]];
Java中是否有类似于块的内容?如果是这样,我将如何使用它? ...的语法是什么?
Is there anything like a block in Java? If so, how would I use it? What's the syntax to...
- 将其用作函数参数吗?
- 在函数中调用所说的块吗?
- 为块分配一个值吗?
我听说过一些关于关闭器"的信息,但是我不确定它们是什么或如何使用它们.
I've heard a little bit about "closures," but I'm not so sure what they are or how to use them.
推荐答案
在Java中,执行此操作的方法是使用接口.最基本的接口是Runnable
,它具有方法run
.
In Java, the way to do this is to use an interface. The most basic interface for this is Runnable
which has a method run
.
...的语法是什么
What's the syntax to...
将其用作函数参数吗?
void foo(Runnable r)
调用函数中的所说的块吗?
call said block in the function?
r.run();
为块分配一个值?
assign a value to the block?
在Java 8之前,您必须执行以下操作:
Before Java 8 you had to do something like this:
Runnable r = new Runnable() {
@Override
public void run() {
// do something
}
}
现在您可以这样做:
Runnable r = () -> { // do something }
包含->
的表达式称为lambda.刹车()
是您可以编写任何参数的位置,但是Runnable
的方法run
没有任何参数.您也可以将Runnable
传递给方法,而无需提及Runnable
:
An expression involving ->
is called a lambda. The brakets ()
are where you would write any parameters, but the method run
of Runnable
doesn't have any parameters. You can also pass a Runnable
to a method without mentioning Runnable
:
foo(() -> { // do something });
Java 8引入了许多新接口,其中该方法可以返回值或接受参数.
Java 8 introduced many, many new interfaces where the method can return a value or accept parameters.
这篇关于是否有Java中的Objective-C块之类的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!