在 Java 中创建 MethodExpression(并在 JSF 中使用)

Create MethodExpression in Java (and use in JSF)

几天来,我一直在尝试让一个具有自动完成功能的 "generic" 对话框发挥作用。事实证明,我只是在 "wrong way" 创建 MethodExpression。所以我想我应该在这里记录下来。

重申一下:您想动态创建 MethodExpression,将其存储在 属性 中并在 JSTL 模板或 JSF 页面中使用它。

例如:

// Template
<c:forEach items="#{property.subItems}" var="subitem">
  <ui:include src="editor.xhtml">
    <ui:param name="autocompleteMethod" value="#{subitem.autocompMethod}" />
  </ui:include>
</c:forEach>

// editor.xhtml
// We're using RichFaces (unfortunately), but this is just an example
<rich:autocomplete mode="cachedAjax" minChars="2"
      autocompleteMethod="#{autocompleteMethod}"
/>

我在 http://javaevangelist.blogspot.co.at/2012/10/jsf-2x-tip-of-day-programmatically_20.html

找到了解决方案
public static MethodExpression createMethodExpression(String methodExpression, Class<?> expectedReturnType, Class<?>[] expectedParamTypes) {
    FacesContext context = FacesContext.getCurrentInstance();
    return context.getApplication().getExpressionFactory()
            .createMethodExpression(context.getELContext(), methodExpression, expectedReturnType, expectedParamTypes);
}

然后您可以创建一个 MethodExpression 并将其存储在 属性 中。对于 RichFaces 自动完成,签名为:List<String> autocomplete(String prefix)

@SuppressWarnings("rawtypes") // Generics use type erasure
Class<List> retType = List.class;
Class<?>[] paramTypes = {String.class};
MethodExpression autocompleteMethod = createMethodExpression("#{myBean.myAutocomplete}", retType, paramTypes);
// In the questions example, we'd need to set a property here:
this.autocompMethod = autocompleteMethod;

然后有合适的getter:

MethodExpression getAutocompMethod() {
    return this.autocompMethod;
}