Java:参数化可运行
标准的 Runnable 接口只有非参数化的 run() 方法。还有 Callable
接口,其中 call()
方法返回泛型类型的结果。我需要传递通用参数,如下所示:
interface MyRunnable<E> {
public abstract void run(E reference);
}
Is there any standard interface for this purpose or I must declare that basic one by myself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
通常,您可以使用支持通用输入参数的类来实现 Runnable 或 Callable ;例如
Typically you would implement
Runnable
orCallable
with a class that supports a generic input parameter; e.g.Java 8 包括
java.util.function.Consumer ;
与单个非默认方法voidaccept(T t)
的接口。该包中还有许多其他相关接口。
Java 8 includes the
java.util.function.Consumer<T>
interface with the single non-default methodvoid accept(T t)
.There are many other related interfaces in that package.
还有
com.google.common.base.Function
,来自Google 集合番石榴。如果将输出类型设置为
?
或Void
(并且始终返回null
),则可以将其用作的替代方案带有输入参数的可运行
。这样做的优点是能够使用 Functions.compose 来转换输入值,Iterables.transform 将其应用到集合的每个元素等。
There is also
com.google.common.base.Function<F, T>
fromGoogle CollectionsGuava.If you set the output type to
?
orVoid
(and always have it returnnull
) you can use it as an alternative toRunnable
with an input parameter.This has the advantage of being able to use
Functions.compose
to transform the input value,Iterables.transform
to apply it to every element of a collection etc.一般来说,如果您想将参数传递给
run()
方法,您将使用带有参数的构造函数对Runnable
进行子类化。例如,您想要这样做:
您需要这样做:
您将实现类似于下面的
YourRunnable
:Generally if you wanna pass a parameter into the
run()
method you will subclassRunnable
with a constructor that takes a parameter.For example, You wanna do this:
You need to do this:
You will implement
YourRunnable
similar to below:我建议像原始问题中那样定义一个接口。此外,通过使接口特定于其应该执行的操作来避免弱类型,而不是像
Runnable
这样无意义的接口。I suggest defining an interface as done in the original question. Further, avoid weak typing by making the interface specific to what it is supposed to do, rather than a meaning-free interface like
Runnable
.