我正在寻找一种方法将代码块传递给方法,然后该方法将对传递给方法的其他参数执行操作,获取这些操作的结果,并将这些结果传递给传递给方法的代码块.为清楚起见:
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();
}
Run Code Online (Sandbox Code Playgroud)
我希望能够在任何需要打开文件,在流上运行一些代码并关闭流的地方重用runOnFile.
我真正想要做的是更复杂,除了FileInputStream之外还使用其他库,但我希望实现的结构是相同的.
谢谢你的帮助!
这是一个将函数复制到堆上,将其设置为可执行文件并调用它的程序。
#include <iostream>
#include <iomanip>
#include <csignal>
#include <Windows.h>
using std::cout;
#define RET 0xC3
void printBytes(void* start, uintptr_t numBytes) {
std::ios_base::fmtflags savedFlags(cout.flags());
cout << std::hex << std::uppercase << std::setfill('0');
bool lineComplete = false;
for (unsigned int byte = 0; byte < numBytes; byte++) {
lineComplete = byte % 4 == 3;
cout << std::setw(2)
<< (int)*((uint8_t*)start + byte)
<< (lineComplete ? '\n' : ' ');
}
cout << (lineComplete ? "\n" : "\n\n");
cout.flags(savedFlags);
}
uint8_t* findByte(void* start, uint8_t targetByte) …Run Code Online (Sandbox Code Playgroud)