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中的注解解析机制。

  • 相关阅读:
    3-2 表的增删改查
    3-1 存储引擎的介绍
    2-1 库的增删改查
    1-4 初识sql语句
    1-3 mysql的安装和基本管理
    1-2 数据库概述
    1-1 数据库管理软件的由来
    4-6 IO模型对比
    《测试软件工程师》11,13 测试用例格式
    《软件测试工程师》10 测试环境搭建
  • 原文地址:https://www.cnblogs.com/silenceshining/p/11695776.html
Copyright © 2011-2022 走看看