hellzone
hellzone

Reputation: 5236

How to create a function that takes print method reference as argument?

I want to create a method that takes print method reference as argument. Is there any way to create a method like below?

public static void main(String [] args) { 
    runFunction(System.out::print);   
}

public static void runFunction(MethodRef methodRef){
    methodRef("test");
}

EDIT:

I have created a functional interface like;

public interface Generatable<T> {
    void generate(T t);
}

And I updated my runFunction as;

public static void acceptFunction(Generatable generatable){
    generatable.generate("test");
}

this method works perfectly but I still don't get how it works. I mean how it calls print method when I call generate("test").

Upvotes: 1

Views: 56

Answers (2)

Christopher Jung
Christopher Jung

Reputation: 103

Yes, like Prashant said. But if you use a functional interface you better add a generic type like that:

public static void runFunction(Consumer<String> consumer){
    consumer.accept("test");
}

For more functional interfaces you can take a look at https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html

Upvotes: 4

Prashant
Prashant

Reputation: 5383

Yes, you can use a Consumer as:

public static void runFunction(Consumer consumer){
    consumer.accept("test");
}

Side note: Functional programming is only supported with Java 8 +. So if you are using any version of Java below 8, this will not work and there is no simple way of fulfilling your requirement.

Upvotes: 1

Related Questions