【问题标题】:SpEL getMethod don't workSpEL getMethod 不起作用
【发布时间】:2014-09-25 16:21:31
【问题描述】:

假设我有一个类 foo.PoJo,它有一个静态公共方法 String,根据offical reference,这段代码应该返回一个 Method 实例。

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 对象,因此您可以访问该对象的静态方法和字段,但是 Method getMethod(String name, Class... parameterTypes) 函数只是一个公共方法不是静态的,因此引发了异常。 如果我是对的,参考可能需要更新。有人知道吗?

【问题讨论】:

  • 您发布的代码适用于 Spring 4.x。

标签: java spring spring-el


【解决方案1】:

T() 实际上返回类实例,您可以访问在Foo 本身上声明的静态方法。在 Java 中,您必须使用 Foo.class.getMethod()

看起来 Spring 在 3.1 中增加了对访问类方法的支持;我只在使用 3.0.x 时遇到你的失败。

当前的 Spring Framework 版本是 4.1.0。

编辑:

Confirmed - Fixed in 3.1.3.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2021-08-25
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多