自定义java注解

自定义java注解

用处

1、编译检查
2、反射时可以通过注解来选择某个属性或者方法或者参数
3、可以生成帮助文档(Swagger2)
4、帮助查看代码(@Override)

// 目标放在哪里
@Target({ElementType.FIELD,ElementType.PARAMETER}) 
// 保留策略  一般使用RUNTIME
@Retention(RetentionPolicy.RUNTIME) 
// 是否存入文档
@Documented
public @interface NotNull {

    String msg() default "参数不能为空";

}
public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration  类,接口(包括注解类型),枚举*/
    TYPE,
    /** Field declaration (includes enum constants) 
    属性上使用
*/
    FIELD,

    /** Method declaration  方法上使用 */
    METHOD,

    /** Formal parameter declaration  形式参数上使用*/
    PARAMETER,

    /** Constructor declaration  构造器上使用*/
    CONSTRUCTOR,

    /** Local variable declaration 局部变量上使用*/
    LOCAL_VARIABLE,

    /** Annotation type declaration 注解类型使用 */
    ANNOTATION_TYPE,

    /** Package declaration 包上使用*/
    PACKAGE,
    
    /**
     * Type parameter declaration  类型参数使用
     */
    TYPE_PARAMETER,

    /**
     * Use of a type 使用类型
     */
    TYPE_USE
}

就可以在需要用到注解的地方使用

   public String getUserName(@NotNull String id) { }
// 通过反射就能选择 注解上的属性、方法、参数等信息 
 Parameter[] parameters = signature.getMethod().getParameters();

        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            //Java自带基本类型的参数(例如Integer、String)的处理方式
            if (isPrimite(parameter.getType())) {
                // 找到@NotNull标注的参数
                NotNull notNull = parameter.getAnnotation(NotNull.class);

                if (notNull != null && (args[i] == null || "".equals(args[i]) ) ) {
                    throw new RuntimeException(parameter.toString() + notNull.msg());
                }
                continue;
            }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值