2013-03-03 54 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... 
     } 
    } 
} 
相關問題