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

猜你喜欢

转载自www.cnblogs.com/silenceshining/p/11695776.html