• java注解使用示例


    举例说明java注解的使用:设置非空注解,当属性未进行赋值时,给出错误提示。

    简单实体类:

    package com.test.annotation;
    
    public class Person {
        @NotNullAnnotation
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Person [name=" + name + "]";
        }
    
    }

    注解定义:

    package com.test.annotation;
    
    import static java.lang.annotation.ElementType.FIELD;
    import static java.lang.annotation.RetentionPolicy.RUNTIME;
    
    import java.lang.annotation.Retention;
    import java.lang.annotation.Target;
    
    @Retention(RUNTIME)
    @Target(FIELD)
    public @interface NotNullAnnotation {
    
    }

    使用示例:

    package com.test.annotation;
    
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Field;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
    
            Person person = new Person();
            //person.setName("hello");
            Class clazz = person.getClass();
            Field field = clazz.getDeclaredField("name");
            field.setAccessible(true);
            Annotation[] annotations = field.getAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation.annotationType().equals(NotNullAnnotation.class)) {
                    if (field.get(person) == null) {
                        System.out.println("name不能为空");
                    }else {
                        System.out.println(field.get(person));
                    }
                }
            }
        }
    
    }

    运行结果:

    name不能为空

    当放开//person.setName("hello");注释以后的运行结果:

    hello

    后续跟进spring中的注解解析机制。

  • 相关阅读:
    JavaScript——封装
    Vue.js——component(组件)
    MySQL数据库——安装教程(5.7版本)
    Vue.js——循环(Java、JSTL标签库、数据库)
    Vue.js——理解与创建使用
    JavaScript——闭包
    自定义最小索引优先队列
    自定义最大索引优先队列
    自定义最小优先队列
    自定义最大优先队列
  • 原文地址:https://www.cnblogs.com/silenceshining/p/11695776.html
Copyright © 2020-2023  润新知