在JSF2中,我声明了函数inspect,它接受java.lang.reflect.Method类型的一个参数,并根据这个参数执行一些注释检查,并返回true或false。问题是,我想从JSF调用这个函数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)}"
/>发布于 2013-07-18 11:20:25
你为什么不直接在服务器端试试呢?在呈现页面之前,您知道是否在当前bean中注释了the method,因此:
@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));
}
}然后您可以从all视图中这样访问:
<h:outputText
value="someMethod is annotated by @MyAnnotation"
rendered="#{inspectorBean.inspectMethod('completeClassName','methodName')}"
/>发布于 2013-07-18 05:11:11
如果使用EL > 2.2,则不需要自定义EL-函数。您可以使用参数直接从ManagedBean调用该方法:
#{someClass.someMethod('foo', 42)}否则,您必须在函数之前声明名称空间并使用它:
#{namespace:inspect(someClass.someMethod)}你可以找到一个good explanation here。
但我不确定这在你的案子中是否有效。即使可以将java.lang.reflect.Method作为参数传递(从未尝试过),该方法如何获得它们的参数?没人能超过他们。
https://stackoverflow.com/questions/17711613
复制相似问题