簡體   English   中英

如何使用反射API獲取方法的參數

[英]How to get parameters of a method using reflection api

我有一個被攔截的方法。 我在傳遞給方法的參數之一上放置了注釋。 我想知道使用該特定注釋注釋哪個參數,並想獲取其值。

@AccessControlled
public String getEmployees(@EmployeeId String id, String type) {
}

InvocationContext我得到了該方法。 當我調用context.getParameters()我得到了一個傳遞給該方法的值數組。

我沒有在方法對象上看到任何名為getParameters()的方法。

我該怎么做?

在我看來,如果ctx是您的InvocationContext ,則您需要ctx.getMethod().getParameterAnnotations()

如果您具有java.lang.reflect.Method實例m ,則您
可以使用此代碼檢查其對AccessControlled注釋。

        Annotation[] anns = m.getAnnotations();
        for (Annotation ann : anns){
            Class clazz = ann.annotationType();
            if (clazz == AccessControlled.class){
                // do something here
            }
        }

我假設您知道如何到達m實例。

這就是我做的

int index = -1;
for (int i = 0; i < parameterAnnotations.length; i++) {
    for (int j = 0; j < parameterAnnotations[i].length; j++) {
        if (parameterAnnotations[i][j].annotationType() == EmployeeId.class) {
            index = i;
            break;
        }
    }
    if (index > -1) {
        break;
    }
}
System.out.println(context.getParameters()[index]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM