获取方法的参数名字以及参数类型

2018年02月27日 网络转载 暂无评论

1.测试类参数

[code]

public JsonResult<String> test(@SocketParam("a") String a) {//自定义注解的参数和方法的参数名字相同
JsonResult<String> reSocket = new JsonResult<>();
reSocket.setResult("dddd");
reSocket.setStatus(JsonResult.SUCCESS);
System.out.println(a);

return reSocket;
}

2.获取参数名字

Method[] methods = cla.getMethods();//获取类下的所有方法 cla是该方法的类

for(Method method:methods){
Annotation[][] parameterAnnotations = method.getParameterAnnotations();

if (parameterAnnotations != null && parameterAnnotations.length > 0) {
String[] parameterNames = new String[parameterAnnotations.length];
int m = 0;

for (Annotation[] parameterAnnotation : parameterAnnotations) {
for (Annotation annotation : parameterAnnotation) {
if (annotation instanceof SocketParam) {
SocketParam param = (SocketParam) annotation;
parameterNames[m++] = param.value();
}
}
}

system.out.println(Arrays.toString(parameterNames));
}

}
}

类型 method.getParameterTypes();

[/code]
http://ask.csdn.net/questions/386684
[code]
public class Demo1 {

    public static void main(String[] args) {
        f1(Test.class);
    }

    private static <T> void f1(Class<T> cls) {
        Method[] methods = cls.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            method.setAccessible(true);
            Parameter[] parameters = method.getParameters();
            for (int j = 0; j < parameters.length; j++) {
                Parameter parameter = parameters[j];
                Annotation[] annotations = parameter.getDeclaredAnnotations();
                for (int k = 0; k < annotations.length; k++) {
                    Annotation annotation = annotations[k];
                    System.out.println(annotation);
                }
            }
        }
    }
} 
[/code]

给我留言

Copyright © 知乐思维 保留所有权利.   Ality主题 粤ICP备14062485

用户登录

分享到: