代码之家  ›  专栏  ›  技术社区  ›  Stormshadow

如何查找带注释的函数参数类型

  •  1
  • Stormshadow  · 技术社区  · 16 年前

    假设我有一个函数

    public int doSomething(@QueryParam("id") String name, int x){ .... }
    

    如何找到带批注的参数“name”的类型。我有一个处理 java.lang.reflect.Method 函数计量与使用实例 getParameterAnnotations() ,我可以得到注释 @QueryParam 但无法访问应用它的参数。我该怎么做?

    1 回复  |  直到 16 年前
        1
  •  2
  •   Bozho    16 年前
    void doSomething(@WebParam(name="paramName") int param) {  }
    
    Method method = Test.class.getDeclaredMethod("doSomething", int.class);
    Annotation[][] annotations = method.getParameterAnnotations();
    
    for (int i = 0; i < annotations.length; i ++) {
        for (Annotation annotation : annotations[i]) {
            System.out.println(annotation);
        }
    }
    

    此输出:

    @javax.jws.WebParam(targetNamespace=, partName=, name=paramName, 
         header=false, mode=IN)
    

    解释-数组是二维的,因为首先你有一个参数数组,然后对于每个参数你有一个注释数组。

    可以使用验证所需注释的类型 instanceof (或) Class.isAssignableFrom(..) .