我有一个文本文件,该文件列出了可以在泵类上执行的所有操作。
文本文件内容示例
Start PayCredit Reject Start PayCredit Reject TurnOff
....
.... so on.
这些是 Pump 类的方法(Start()、Reject() 等)
我需要编写一段代码,可以从文件中一一读取这些方法并执行它们。
public static void main(String[] args) throws IOException
{
Pump gp= new Pump();
File file=new File("C:\\Users\\Desktop\\checker\\check.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line=null;
while((line=br.readLine())!=null)
{
String words[]=line.split(" ");
for(int i=0;i<words.length;i++)
{
String temp=words[i]+"()";
gp.temp; //compilation error
}
}
}
你能告诉我如何实现这个功能吗?
最佳答案
如果您对反射不太熟悉,也许可以尝试使用 Spring Framework 项目中的 org.springframework.util.ReflectionUtils
?
代码会是这样的:
Pump gp = new Pump();
....
String temp = // from text file
....
Method m = ReflectionUtils.findMethod(Pump.class, temp);
Object result = ReflectionUtils.invokeMethod(m, gp);
关于java - 从文本文件中读取方法并在程序中执行它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27353878/