2013-03-03 53 views
0

假设我有一个文件,它的名称是file.txt它由java中反射方法的脚本组成。假设其中一些是:使用输入字符串生成对象和函数反射

new <id> <class> <arg0> <arg1> … creates a new instance of <class> by using 
a constructor that takes the given argument types and stores the result in <id>. 
call <id> <method> <arg0> <arg1> … invokes the specified <method> that 
takes the given arguments on the instance specified by <id> and prints the answer. 
print <id> prints detailed information about the instance specified by <id>. See 
below for Object details. 

该文件中的脚本将作为字符串在程序中拾取。我将如何将其转换为我上面指定的参数进行反射。我瞎了这个!一些代码的帮助位描述将不胜感激,因为我是新来的Java。

回答

1

这首先是解析的问题。你需要做的第一件事是把你的输入分成可管理的块。由于您似乎正在使用空格分隔您的组件,这应该是一件相当容易的事情。

由于每行有一个命令,因此您要做的第一件事是将它们分解成行,然后根据空白将它们分解为单独的字符串。解析是一个足够大的话题,值得自己的问题。

然后,你会一行一行,使用行中第一个单词的if语句来确定应该执行什么命令,然后根据他们正在做什么来解析其他单词。

事情是这样的:

public void execute(List<String> lines){ 
    for(String line : lines){ 
     // This is a very simple way to perform the splitting. 
     // You may need to write more code based on your needs. 
     String[] parts = lines.split(" "); 

     if(parts[0].equalsIgnoreCase("new")){ 
      String id = parts[1]; 
      String className = parts[2]; 
      // Etc... 
     } else if(parts[0].equalsIgnoreCase("call")){ 
      String id = parts[1]; 
      String methodName = parts[2]; 
      // Etc... 
     } 
    } 
} 
相关问题