栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Method.getParameterAnnotations()解释,测试用例,使用场景

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Method.getParameterAnnotations()解释,测试用例,使用场景

Method.getParameterAnnotations
  • 返回值解释
  • 代码演示
    • ZQRequestParam
    • ZQValid
    • DemoServiceImpl
    • Test
  • 输出结果
  • 使用场景

返回值解释

Method.getParameterAnnotations()各个维度理解:
返回值:annotations
返回值类型:Annotation[][]
返回值:annotations:
位置:annotations[i][j],第i个参数,第j个注解,整体表示一个注解类型
图示:

代码演示 ZQRequestParam
import java.lang.annotation.*;

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ZQRequestParam {
    String value() default "";
}
ZQValid
@Target({ METHOD, FIELD, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
public @interface ZQValid {
    String value() default "";
}
DemoServiceImpl
public class DemoServiceImpl {
    public void testGetParameterAnnotations(@ZQRequestParam("name") @ZQValid("name1") String name,
                                            @ZQRequestParam("age") int age,
                                            @ZQRequestParam("telphone") String telphone){

    }
}
Test
public class Test {
    public static void main(String[] args) throws NoSuchMethodException {
        Class clazz = DemoServiceImpl.class;
        Method method = clazz.getMethod("testGetParameterAnnotations", String.class, int.class, String.class);
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            System.out.println("我是第" + (i + 1) + "个参数,共有" + annotations[i].length + "个注解");
            for (int j = 0; j < annotations[i].length; j++) {
                if (annotations[i][j] instanceof ZQRequestParam) {
                    System.out.println("第" + (i + 1) + "参数,第" + (j + 1) + "个注解,ZQRequestParam.value=" + ((ZQRequestParam) annotations[i][j]).value());
                } else if (annotations[i][j] instanceof ZQValid) {
                    System.out.println("第" + (i + 1) + "参数,第" + (j + 1) + "个注解,ZQValid.value=" + ((ZQValid) annotations[i][j]).value());
                }

            }
        }
    }
}
输出结果

使用场景

用于访问MVC前端通过HTTPS访问后端,获得形参参数位置-参数注解位置的注解,并整理出访问方法的形参位置与形参名称name(如@RequestParam(value=“name”))做映射关系。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/943805.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号