[英]Acquire method reference in JSF EL
在JSF 2中,我聲明了函數inspect
,它接受一個類型為java.lang.reflect.Method
參數,並基於此參數執行一些注釋檢查並返回true
或false
。 問題是我想從JSF EL調用此函數inspect
以能夠根據返回值修改UI,但是我無法獲取目標方法的引用以將其作為函數的參數傳遞,所以我想請問該怎么做?
例
package some.pkg;
@ManagedBean( name = "someClass" )
public class SomeClass {
@MyAnnotation
public void someMethod( String arg1, Integer arg2 ) { /* ... */ }
}
JSF函數聲明
<function>
<function-name>inspect</function-name>
<function-class>some.pkg.Inspector</function-class>
<function-signature>boolean inspect(java.lang.reflect.Method)</function-signature>
</function>
來自JSF的所需調用,但不起作用
<h:outputText
value="someMethod is annotated by @MyAnnotation"
rendered="#{inspect(someClass.someMethod)}"
/>
這也是可以接受的,但是它不太舒適
<h:outputText
value="someMethod is annotated by @MyAnnotation"
rendered="#{inspect(some.pkg.SomeClass.someMethod)}"
/>
為什么不只在服務器端嘗試呢? 在呈現頁面之前,您知道在當前bean中是否注釋了該方法 ,因此:
@ManagedBean( name = "someClass" )
public class SomeClass {
boolean annotated = false;
public boolean isAnnotated(){
return annotated;
}
@PostConstruct
public void postConstruct(){
if (inspect(this.getClass().getMethod("someMethod")){
annotated=true;
}
}
}
在您的xhtml頁面中:
<h:outputText
value="someMethod is annotated by @MyAnnotation"
rendered="#{someClass.annotated}"
/>
您甚至可以修改它以使用參數並即時計算它:
//Notice in this case we're using a METHOD, not a GETTER
public boolean annotated(String methodName){
return inspect(this.getClass().getMethod(methodName);
}
這樣稱呼它:
<h:outputText
value="someMethod is annotated by @MyAnnotation"
rendered="#{someClass.annotated('methodName')}"
/>
或者,您可以使用@ApplicationScoped
托管Bean來從每個單個視圖訪問它:
@ManagedBean
@ApplicationScoped
public class InspectorBean{
public boolean inspectMethod(String className, String methodName){
return inspect(Class.forName(className).getMethod(methodName));
}
}
然后,您可以從所有視圖中進行訪問:
<h:outputText
value="someMethod is annotated by @MyAnnotation"
rendered="#{inspectorBean.inspectMethod('completeClassName','methodName')}"
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.