Java 自定义注释@interface的用法

最简单的待校验的注解定义

@Documented
@Constraint(validatedBy = ExistBlankByListValidator.class)
@Target({PARAMETER})
@Retention(RUNTIME)
public @interface ExistBlankByList {
    String message() default "{annotation.ExistBlankByList.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class ExistBlankByListValidator implements ConstraintValidator<ExistBlankByList, List> {
    private String msg = "";

    @Override
    public void initialize(ExistBlankByList existBlankByList) {
        msg = existBlankByList.message();
    }

    @Override
    public boolean isValid(List value, ConstraintValidatorContext context) {
        if (null == value) {
            return false;
        }
        return value.stream().noneMatch(StringUtils::isEmpty);
    }
}
Target值
public enum ElementType {  
     TYPE, // 指定适用点为 class, interface, enum  
     FIELD, // 指定适用点为 field  
     METHOD, // 指定适用点为 method  
     PARAMETER, // 指定适用点为 method 的 parameter  
     CONSTRUCTOR, // 指定适用点为 constructor  
     LOCAL_VARIABLE, // 指定使用点为 局部变量  
     ANNOTATION_TYPE, //指定适用点为 annotation 类型  
     PACKAGE // 指定适用点为 package  
} 
Retention值
public enum RetentionPolicy {  
     SOURCE, // 编译器处理完Annotation后不存储在class中  
     CLASS, // 编译器把Annotation存储在class中,这是默认值  
     RUNTIME // 编译器把Annotation存储在class中,可以由虚拟机读取,反射需要  
} 

 

转载于:https://www.cnblogs.com/fqybzhangji/p/10369715.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java自定义元注解通常用于对注解进行注释和描述,其使用方法如下: 1. 定义一个注解,使用@Target、@Retention、@Documented三个元注解对注解进行描述。 2. 使用@Inherited元注解,表示注解可以被继承。 3. 在需要使用注解的类、方法、属性等上面使用定义的注解,通过反射获取注解信息。 示例代码如下: @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface CustomAnnotation { String value() default ""; } 在需要使用注解的类、方法、属性等上面使用定义的注解: @CustomAnnotation(value = "这是一个自定义注解") public class Test { @CustomAnnotation(value = "这是一个字段注解") private String name; @CustomAnnotation(value = "这是一个方法注解") public void sayHello() { System.out.println("Hello World!"); } } 通过反射获取注解信息: Class testClass = Test.class; CustomAnnotation annotation1 = (CustomAnnotation) testClass.getAnnotation(CustomAnnotation.class); System.out.println(annotation1.value()); // 输出 "这是一个自定义注解" Field nameField = testClass.getDeclaredField("name"); CustomAnnotation annotation2 = nameField.getAnnotation(CustomAnnotation.class); System.out.println(annotation2.value()); // 输出 "这是一个字段注解" Method sayHelloMethod = testClass.getDeclaredMethod("sayHello"); CustomAnnotation annotation3 = sayHelloMethod.getAnnotation(CustomAnnotation.class); System.out.println(annotation3.value()); // 输出 "这是一个方法注解"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值