2014-07-13 64 views
0

我有一個問題: 我開發微型webapp(Java)解析,編譯用戶源,運行幾個管理定義的測試並返回響應 - 用戶源成功通過所有測試,編譯失敗或執行因時間限制而終止。所以爲了編譯,我需要知道什麼是用戶代碼的類(public class SomeClass)。這裏是我的代碼:如何解析Java源代碼?

String source = task.method; 
StringReader sourceReader = new StringReader(source); 
BufferedReader reader = new BufferedReader(sourceReader); 

String labClassName = null; 
while (labClassName == null) { 
    String line = reader.readLine(); 

    if (line.startsWith("public")) { 

     Scanner classNameScanner = new Scanner(line).useDelimiter("\\s"); 
     classNameScanner.next(); 
     classNameScanner.next(); 
     labClassName = classNameScanner.next(); 
    } 
} 

reader.close(); 

對我來說這是很醜陋的建築,但它的作品,我獲取必要的類名,但我覺得還有其他更便捷的方式找到一些字符串,它與「公共類開始「經過幾次進口。這裏的用戶來源的例子之一(來源有很大的不同,他們有的開始用簡單的「公共課」,有的開始與進口,進口的數量是隨機的 - 只需要此代碼):

import java.io.IOException; 
import java.io.InputStream; 
import java.util.Iterator; 
import java.util.NoSuchElementException; 

public class ISToIteratorAdapter implements Iterator<Byte> { 

    public ISToIteratorAdapter(InputStream is) { 
     this.is = is; 
     try { 
      this.last = is.read(); 
     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 

    private final InputStream is; 
    private int last = -1; 

    @Override 
    public boolean hasNext() { 
     return last != -1; 
    } 

    @Override 
    public Byte next() { 
     try { 
      if (last != -1) { 
       int tmp = last; 
       last = is.read(); 
       return (byte) tmp; 
      } else { 
       throw new NoSuchElementException(); 
      } 
     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 

    @Override 
    public void remove() { 
     throw new UnsupportedOperationException(); 
    } 
} 
+0

這聽起來很奇特。如果你知道類名:那麼呢?至少對於調用,您還必須知道該包(如果有的話)。你如何知道要調用的構造函數和方法?如果它是抽象的呢?等等...... – laune

+0

如果你可以編譯這個類,你應該知道這個名字。我也會給你'公共最終課SomeClass'。 – biziclop

+0

不要打擾。太難。讓用戶告訴你。 – EJP

回答

0

如果你能想到的源文件不包含任何「迴避動作」或技巧絆倒你的代碼,然後

Pattern pat = Pattern.compile("^\\s*public\\s+class\\s+(\\w+).*$"); 

String line = reader.readLine(); 
Matcher mat = pat.matcher(line); 
if(mat.matches()){ 
    String classname = mat.group(1); 
    // ... 
} 

會發現包含空格,關鍵字的訂單「公共」和「類」和類名。