简体   繁体   中英

In Java 8, how do I make a method reference to a method that takes no parameters and returns void?

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?

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");
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM