java自定义注解

注解的原理是反射。

简单例子

定义一个属性注解:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String description() default "默认注解";
    int length();
}

注解的使用:

public class MyAnnotationTest {
    private static final Logger logger = LoggerFactory.getLogger(MyAnnotationTest.class);
    @MyAnnotation(description = "用户名",length = 13)
    private String username;

    public static void main(String[] args) {
        // 获取类模板
        Class c = MyAnnotationTest.class;
        for(Field f : c.getDeclaredFields()){
            // 判断这个字段是否有MyField注解
            if(f.isAnnotationPresent(MyAnnotation.class)){
                MyAnnotation annotation = f.getAnnotation(MyAnnotation.class);
                logger.info("字段:{},描述:{},长度:{}",
                        f.getName(),annotation.description(), annotation.length());
            }
        }
    }
}

你可能感兴趣的:(java,开发语言,前端)