[英]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.