Reputation: 67474
I have a bunch of methods with this signature:
public void sideEffects() {...}
public void foo() {...}
public void bar() {...}
(That is, they return void and take no parameters) And I'd like to be able to populate a List by doing something like this:
list.add(MyClass::sideEffects);
list.add(MyClass::foo);
list.add(MyClass::bar);
But, I'm unable to find a built in @FunctionalInterface
in the java.util.function
package that supports this signature. Will I have to create my own @FunctionalInterface
for this?
Upvotes: 3
Views: 2309
Reputation: 67474
In this case, java.lang.Runnable
has the signature you're looking for and is a @FunctionalInterface
. You can use this for this purpose, though I'm not sure if this is a good or bad practice.
The code will look like this:
package com.sandbox;
import java.util.ArrayList;
import java.util.List;
public class Sandbox {
public static void main(String[] args) {
List<Runnable> list = new ArrayList<>();
list.add(Sandbox::sideEffects);
list.add(Sandbox::foo);
list.add(Sandbox::bar);
for (Runnable runnable : list) {
runnable.run();
}
}
public static void sideEffects() {
System.out.println("sideEffects");
}
public static void foo() {
System.out.println("foo");
}
public static void bar() {
System.out.println("bar");
}
}
Upvotes: 8