如何使用反射api获取方法的参数

时间:2014-02-04 11:15:10

标签: java java-ee reflection interceptor

我有一个截获的方法。我有一个注释放在传递给方法的其中一个参数上。我想知道哪个参数使用该特定注释进行注释,并希望获得其值。

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

InvocationContext我得到了方法。当我调用context.getParameters()时,我得到一个传递给该方法的值数组。

我没有在方法对象上看到任何名为getParameters()的方法。

我该如何做到这一点?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

如果您拥有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实例。

答案 2 :(得分:0)

我就这样做了

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]);