2010-12-03 20 views
1

根據MVEL的文檔,可以在腳本中導入靜態java方法:http://mvel.codehaus.org/Programmatic+Imports+for+2.0。以下示例來自該頁面,但不起作用(我得到一個錯誤:無法訪問屬性(空父母):時間)。什麼可能是錯的?無法使用MVEL導入靜態方法

import java.io.Serializable; 
import org.mvel2.MVEL; 
import org.mvel2.ParserContext; 

public class Test { 

    public static void main(String[] args) { 

     ParserContext ctx = new ParserContext(); 
     try { 
      ctx.addImport("time", System.class.getMethod("currentTimeMillis", long.class)); 
     } 
     catch (NoSuchMethodException e) { 
      // handle exception here. 
     } 

     Serializable s = MVEL.compileExpression("time();", ctx); 
     Object ans = MVEL.executeExpression(s); 
     System.out.println(ans.toString()); 

    } 

} 

回答

2

getMethod的第二個參數用於參數類型,它不用於方法的返回類型。

改變這一行:

System.class.getMethod("currentTimeMillis", long.class) 

與此:

System.class.getMethod("currentTimeMillis")