[英]Pass Lambda That Takes Arguments to Method
I'm looking for a way to pass a code block to a method, which will then perform actions on other arguments passed to method, take the results of those actions, and pass those results to the code block passed to the method. 我正在寻找一种方法将代码块传递给方法,然后该方法将对传递给方法的其他参数执行操作,获取这些操作的结果,并将这些结果传递给传递给方法的代码块。 For clarity: 为清楚起见:
private static void method1(String filename, int sheetNum) {
runOnSheet(filename, () -> {
doStuffWithStream(FileInputStream fileStream); // Does something with a file stream
doOtherStuffWithStream(FileInputStream fileStream); // Does something else with a file stream
});
}
// Elsewhere
private static void runOnFile(String fileName, Runnable block1) {
try {
fileStream = new FileInputStream(fileName);
} catch (IOException e) {
e.printStackTrace();
}
block1.run(); // I'd like to pass fileStream to this code block. Ideally i could do block1.run(fileStream );
fileStream.close();
}
I want to be able to reuse runOnFile anywhere I need to open a file, run some code on the stream, and close the stream. 我希望能够在任何需要打开文件,在流上运行一些代码并关闭流的地方重用runOnFile。
What I actually want to do is more complicated, and uses other libraries in addition to FileInputStream, but the structure of what I wish to accomplish is the same. 我真正想要做的是更复杂,除了FileInputStream之外还使用其他库,但我希望实现的结构是相同的。
Thanks for any help! 谢谢你的帮助!
Java 8+ has a Class called Consumer
that can be used for your usecase: https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html Java 8+有一个名为Consumer
,可用于您的用例: https : //docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html
private static void method1(String filename, int sheetNum) {
runOnFile(filename, (fileStream) -> {
doStuffWithStream(fileStream);
doOtherStuffWithStream(fileStream);
});
}
// Elsewhere
private static void runOnFile(String fileName, Consumer<FileInputStream> block1) {
try {
fileStream = new FileInputStream(fileName);
} catch (IOException e) {
e.printStackTrace();
}
block1.accept(fileStrean);
fileStream.close();
}
EDIT: As suggested by Dimitri using the try-with-resource
syntax: 编辑:正如Dimitri使用try-with-resource
语法所建议的那样:
// Elsewhere
private static void runOnFile(String fileName, Consumer<FileInputStream> block1) {
try (FileInputStream fis = new FileInputStream(fileName)) {
block1.accept(fis);
} catch (IOException e) {
e.printStackTrace();
}
}
Try something like this: 尝试这样的事情:
private static void method1(String filename, int sheetNum)
{
try ( final FileInputStream fileStream = new FileInputStream(filename))
{
runOnSheet(filename, () ->
{
doStuffWithStream(fileStream); // Does something with a file stream
doOtherStuffWithStream(fileStream); // Does something else with a file stream
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.