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

1.测试类参数

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

http://ask.csdn.net/questions/386684
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);
                }
            }
        }
    }
} 
原文链接:,转发请注明来源!

Leave a Reply

You must be logged in to post a comment.