In Java 8, how to reference a method without parameters and return void?
•
Java
I have a bunch of methods with this signature:
public void sideEffects() {...}
public void foo() {...}
public void bar() {...}
(that is, they return void and have no parameters) and I want to be able to populate the list by doing the following:
list.add(MyClass::sideEffects); list.add(MyClass::foo); list.add(MyClass::bar);
However, I can't use Java. Net that supports this signature util. The built-in @ functionalinterface. Was found in the function package Do I have to create my own @ functionalinterface for this?
Solution
In this case, Java Lang. runnable has the signature you are looking for and is @ functionalinterface You can use this for this purpose, but I'm not sure if it's a good thing or a bad thing
The code is as follows:
package com.sand@R_949_2419@;
import java.util.ArrayList;
import java.util.List;
public class Sand@R_949_2419@ {
public static void main(String[] args) {
List<Runnable> list = new ArrayList<>();
list.add(Sand@R_949_2419@::sideEffects);
list.add(Sand@R_949_2419@::foo);
list.add(Sand@R_949_2419@::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");
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
