java 自定义注解小示例

目录结构 自定义一个注解类

package Annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//元注解(注解注解的注解)
@Target(ElementType.TYPE)//定义该注解类注解的位置
@Retention(RetentionPolicy.RUNTIME)//定义该注解什么时候启动
public @interface VIP {
          
   
    int level();
}

定义一个用户类

package Annotation;

@VIP(level = 2)
public class Account {
          
   
    private String id;
    private String name;

    public Account() {
          
   
    }

    public Account(String id, String name) {
          
   
        this.id = id;
        this.name = name;
    }

    public String getId() {
          
   
        return id;
    }

    public void setId(String id) {
          
   
        this.id = id;
    }

    public String getName() {
          
   
        return name;
    }

    public void setName(String name) {
          
   
        this.name = name;
    }

    @Override
    public String toString() {
          
   
        return "Account{" +
                "id=" + id +  +
                ", name=" + name +  +
                };
    }
}

启动

package Annotation;

public class Main {
          
   
    public static void main(String[] args) {
          
   
        Account account = new Account();
        account.setId("1");
        account.setName("压缩");

        Class<? extends Account> aClass = account.getClass();
        VIP annotation = aClass.getAnnotation(VIP.class);
        if (annotation != null){
          
   
            int level = annotation.level();
            if (level == 1){
          
   
                System.out.println(account.getName()+":"+"尊贵1");
            }else if(level == 2){
          
   
                System.out.println(account.getName()+":"+"尊贵2");
            }else if (level == 3){
          
   
                System.out.println(account.getName()+":"+"尊贵3");
            }
        }
    }
}

效果

经验分享 程序员 微信小程序 职场和发展