zoukankan      html  css  js  c++  java
  • 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中的注解解析机制。

  • 相关阅读:
    LeetCode Notes_#328_奇偶链表
    LeetCode Notes_#203_移除链表元素
    LeetCode Notes_#19_删除链表的倒数第N个节点
    如何选择分类模型的评价指标
    利用类权重来改善类别不平衡
    使用LIME解释黑盒ML模型
    Python机器学习算法:线性回归
    基于RNN自编码器的离群点检测
    用TensorFlow预测纽约市AirBnB租赁价格
    权重不确定的概率线性回归
  • 原文地址:https://www.cnblogs.com/silenceshining/p/11695776.html
Copyright © 2011-2022 走看看