Lambda expressions must be cast to a functional interface. They cannot extend a class as far as I know but I want to know if there is a way to get something similar.
I have java.nio.file.SimpleFileVisitor<Path>
as base class and I want to override a method of it but I wish to do so inside another method. I can do it with an anonymous class this way:
public static void printContent(Path path) throws IOException {
FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
System.out.println(file);
return super.visitFile(file, attrs);
}
};
Files.walkFileTree(path, visitor);
}
Is there a way to remove that load of code with the help of a lambda?
I think the lambda would be (f) -> System.out.println(f);
I thought about forgetting SimpleFileVisitor and creating a equivalent interface with default methods but, how could I select what method to override? Would I need to leave the method I want to override without default implementation? In that case I would need several Interfaces for different cases with different not implemented methods.
Thank you.
Use Delegation. For this task you need a helper class that has to be implemented only once:
Once you have your helper class you can use it together with lambda expressions, e.g.
or