Создать MethodExpression в Java (и использовать в JSF)

Я пытался заставить "общий" диалог с функцией автозаполнения работать уже несколько дней. Оказывается, я просто создавал 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}"
/>

1 ответ

Решение

Я нашел решение в 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;

Тогда имейте соответствующий получатель:

MethodExpression getAutocompMethod() {
    return this.autocompMethod;
}
Другие вопросы по тегам