繁体   English   中英

JSF EL中的获取方法参考

[英]Acquire method reference in JSF EL

在JSF 2中,我声明了函数inspect ,它接受一个类型为java.lang.reflect.Method参数,并基于此参数执行一些注释检查并返回truefalse 问题是我想从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)}"
 />

如果您使用EL> 2.2,则不需要自定义EL功能。 您可以直接使用参数从ManagedBean调用该方法:

#{someClass.someMethod('foo', 42)}

否则,您必须声明一个名称空间并在函数之前使用它:

#{namespace:inspect(someClass.someMethod)}

您可以在这里找到很好的解释

但是我不确定这是否可以解决您的问题。 即使可以将java.lang.reflect.Method作为参数传递(从未尝试过),该Method应该如何获取其参数? 没有人通过。

为什么不只在服务器端尝试呢? 在呈现页面之前,您知道在当前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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM