在EL中使用匿名内部类bean上的参数调用方法

时间:2013-04-30 21:42:47

标签: java jsp el anonymous-inner-class

如果我有一个像这样的匿名内部类对象(其中Foo是一个接口):

Foo foo = new Foo(){
  @Override
  public String hello(Object dummyArg){
    return "hello, world.";
  }
};

我尝试从这样的jsp中调用Foo.hello

${foo.hello('blah')}
它扔了:

javax.el.MethodNotFoundException: Unable to find method [hello] with [1] parameters

但如果没有参数:

Bar bar = new bar(){
  @Override
  public String hello(){
    return "hello, world.";
  }
};

...

${bar.hello()}

它工作正常。为什么呢?

这不是7121303的重复。我正在特别询问匿名的内部课程。使用常规类的实例,它可以使用任意数量的参数。

2 个答案:

答案 0 :(得分:1)

可能需要创建EL函数,您可以通过参数传递。 (http://blog.idleworx.com/2010/04/custom-tags-and-custom-el-functions-in.html

在EL 2.2中引入了对传递方法参数和调用非getter方法的支持。在tomcat上启用EL 2.2(http://code2inspire.wordpress.com/2010/11/05/how-to-enable-el-2-2-on-tomcat-6/

答案 1 :(得分:1)

我不知道您使用的是哪种环境,但我尝试使用tomcat7.0.40并且您的代码运行良好。

一种可能性是,在期望Object时传递String可能会出现问题。可能是一些严格的解析。 你可以试试以下: 将参数存储到pageContext并使用它将值传递给函数,如下所示。

<%
pageContext.setAttribute("argObj", "blah");
%>

${foo.hello(argObj)}