2014-09-25 23 views
0

假設我有一個類foo.PoJo,它有一個靜態公共方法String,根據offical reference,這段代碼應該返回一個Method實例。SpEL getMethod不工作

SpelExpressionParser parser = new SpelExpressionParser(); 
Expression exp = parser.parseExpression("T(foo.PoJo).getMethod('print')"); 
Method m = (Method) exp.getValue(); 

然而,這個代碼將提高一個例外:

Exception in thread "main" org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 49): Method call: Method getMethod(java.lang.String) cannot be found on foo 
.PoJo type 
     at org.springframework.expression.spel.ast.MethodReference.findAccessorForMethod(MethodReference.java:185) 
     at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:107) 
     at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:57) 
     at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:93) 
     at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:66) 
     at com.duowan.realtime.scheduled.batch.temp.PoJo.main(PoJo.java:57) 
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
     at java.lang.reflect.Method.invoke(Method.java:597) 
     at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) 

我的猜測是,T()操作會返回一個Class對象,這樣你就可以訪問該對象的靜態方法和字段但是getMethod方法(String name,Class ... parameterTypes)函數只是一個不是靜態的公共方法,所以引發異常。 如果我是正確的,則可能需要更新。任何人有任何想法?

+0

您發佈的代碼適用於Spring 4.x。 – 2014-09-25 04:44:56

回答

1

T()實際上會返回類實例,您可以訪問在Foo本身上聲明的靜態方法。在Java中,你將不得不使用Foo.class.getMethod()

看起來Spring在3.1中增加了對訪問類方法的支持;我只在使用3.0.x時遇到你的失敗。

當前的Spring Framework版本是4.1.0。

編輯:

Confirmed - Fixed in 3.1.3

+0

是的,我應該改變春天的版本 – 2014-09-25 07:00:00