簡體   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