Java: Parameterized Runnable
Standard Runnable
interface has only non-parametrized run()
method. There is also Callable<V>
interface with call()
method returning result of generic type. I need to pass generic parameter, something like this:
interface MyRunnable<E> {
public abstract void ru开发者_运维知识库n(E reference);
}
Is there any standard interface for this purpose or I must declare that basic one by myself?Typically you would implement Runnable
or Callable
with a class that supports a generic input parameter; e.g.
public class MyRunnable<T> implements Runnable {
private final T t;
public MyRunnable(T t) {
this.t = t;
}
public void run() {
// Reference t.
}
}
Java 8 includes the java.util.function.Consumer<T>
interface with the single non-default method void accept(T t)
.
There are many other related interfaces in that package.
There is also com.google.common.base.Function<F, T>
from Google CollectionsGuava.
If you set the output type to ?
or Void
(and always have it return null
) you can use it as an alternative to Runnable
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.
Generally if you wanna pass a parameter into the run()
method you will subclass Runnable
with a constructor that takes a parameter.
For example, You wanna do this:
// code
Runnable r = new YourRunnable();
r.run(someParam);
//more code
You need to do this:
// code
Runnable r = new YourRunnable(someParam);
r.run();
//more code
You will implement YourRunnable
similar to below:
public class YourRunnable implements Runnable {
Some param;
public YourRunnable(Some param){
this.param = param;
}
public void run(){
// do something with param
}
}
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
.
精彩评论