mschayna
mschayna

Reputation: 1310

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 run(E reference);
}
Is there any standard interface for this purpose or I must declare that basic one by myself?

Upvotes: 20

Views: 18086

Answers (5)

Adamski
Adamski

Reputation: 54715

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.
  }
}

Upvotes: 16

andrewdotn
andrewdotn

Reputation: 34863

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.

Upvotes: 14

finnw
finnw

Reputation: 48639

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.

Upvotes: 8

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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.

Upvotes: 0

jjnguy
jjnguy

Reputation: 138922

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
    }
}

Upvotes: 3

Related Questions