Reputation: 412
I forgot a concept that I used and can't remember it.
For the context, I used to have a method like toString()
which had a parameter. This parameters allowed me to call my method like myMethod(System.out::println)
to print it on the screen, but also to print it in a file with the same syntax.
Does anyone know what can be this parameter? the concept? I think it's kind of a FunctionalInterface but I don't know what it is.
Upvotes: 0
Views: 2006
Reputation: 87221
Would this work for you?
public class C {
static void myMethod(java.io.PrintStream p) {
p.println("Hello!");
}
public static void main(String args[]) {
myMethod(System.out);
}
}
Unfortunately you can't pass System.out.println
directly, because in Java methods (before Java 8) are not first-class objects. All you can do with a method is calling it. As a workaround, you can introduce an interface and create an adapter class.
Upvotes: 0
Reputation: 12939
This goes well with java 8 functional interface:
@FunctionalInterface
static interface MyPrinter {
public void println(String line);
}
static void myMethod(MyPrinter mp) {
mp.println("Hello wolrd");
}
...
public static void main(String[] args) throws IOException {
myMethod(System.out::println);
PrintWriter pw = new PrintWriter("myFile.txt");
myMethod(pw::println);
pw.close(); //never forget to close file output streams!
//EDIT: note that you can of course store your MyPrinter in a variable:
MyPrinter mp = System.err::println;
myMethod(mp);
}
Upvotes: 0
Reputation: 5223
This is called method reference and applies when you know what method you want to call, provided the method already exist.
Because this lambda expression invokes an existing method, you can use a method reference instead of a lambda expression:
Arrays.sort(rosterAsArray, Person::compareByAge);
Available since Java-8.
An exemple using what you want:
public static void function(String s, Consumer<String> f) {
f.accept(s);
}
public static void main(String args[]) {
String test1 = "test";
String test2 = "test2";
function(test1, System.out::println);
function(test2, System.out::println);
function(test1, System.out::print);
function(test2, System.out::print);
}
Upvotes: 2