Reputation: 305
I'm trying to understand Java 8's Lambda expressions. In the example, I want to parse a number of files. For each file, I need to create a new instance of the particular template (which is the same for all the files passed at a time).
If I understood it right, that's what Lambda expressions are good for.
Can anyone please explain to me in simple term how to pass the call to the template's constructor as a parameter? (So that it could be new Template1()
, new Template2()
and so on).
import java.io.File;
public class Parser {
public static void main(String[] args) {
new Parser(new File[]{});
}
Parser(File[] files) {
for (File f : files) {
// How can I pass this as a parameter?
Template t = new Template1();
}
}
public class Template {
// Code...
}
public class Template1 extends Template {
// Code...
}
public class Template2 extends Template {
// Code...
}
}
Upvotes: 3
Views: 2617
Reputation: 108959
You can use a Supplier and constructor reference:
public static void main(String[] args) {
new Parser(new File[]{}, Template1::new);
}
Parser(File[] files, Supplier<Template> templateFactory) {
for (File f : files) {
Template t = templateFactory.get();
}
}
The Function type could be used for a one-argument constructor like Template1(File)
:
public static void main(String[] args) {
new Parser(new File[]{}, Template1::new);
}
Parser(File[] files, Function<File, Template> templateFactory) {
for (File f : files) {
Template t = templateFactory.apply(f);
}
}
The Java 8 API provides a number of standard functional interfaces in the java.util.function package though these typically don't extend beyond two arguments. You can either use 3rd party nary functional interfaces (I made some for KludJe) or write your own.
A custom implementation might look like this:
public static void main(String[] args) {
new Parser(new File[]{}, Template1::new);
}
Parser(File[] files, TemplateFactory templateFactory) {
for (File f : files) {
Template t = templateFactory.createFrom(f);
}
}
public static interface TemplateFactory {
Template createFrom(File file);
}
Upvotes: 10