zoukankan      html  css  js  c++  java
  • Java自己写一个注解

    代码摘自:https://www.cnblogs.com/acm-bingzi/p/javaAnnotation.html

    看如下代码:

    package com.work.AnnotationTest;
    
    import java.lang.annotation.*;
    
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface FruitName {
        String value() default "";
    }
    package com.work.AnnotationTest;
    
    import java.lang.annotation.*;
    
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface FruitColor {
        public enum Color{BLUE,RED,GREEN};
        Color fruitColor() default Color.GREEN;
    }
    package com.work.AnnotationTest;
    
    import java.lang.annotation.*;
    
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface FruitProvider {
        public int id() default -1;
        public String name() default "";
        public String address() default "";
    }
    package com.work.AnnotationTest;
    
    import java.lang.reflect.Field;
    
    public class FruitInfoUtil {
        public static void getFruitInfo(Class<?> clazz){
            String strFruitName = " 水果名称: ";
            String strFruitColor = " 水果颜色: ";
            String strFruitProvicer = " 供应商信息: ";
            Field[] fields = clazz.getDeclaredFields();
            for (Field field:fields){
                if(field.isAnnotationPresent(FruitName.class)){
                    FruitName fruitName = field.getAnnotation(FruitName.class);
                    strFruitName = strFruitName+fruitName.value();
                    System.out.println(strFruitName);
                }else if (field.isAnnotationPresent(FruitColor.class)){
                    FruitColor fruitColor = field.getAnnotation(FruitColor.class);
                    strFruitColor = strFruitColor+fruitColor.fruitColor().toString();
                    System.out.println(strFruitColor);
                }else if (field.isAnnotationPresent(FruitProvider.class)){
                    FruitProvider fruitProvider = field.getAnnotation(FruitProvider.class);
                    strFruitProvicer = "供应商编号: "+fruitProvider.id()+" 供应商名称: " + fruitProvider.name() + " 供应商地址: "+fruitProvider.address();
                    System.out.println(strFruitProvicer);
                }
            }
        }
    }
    package com.work.AnnotationTest;
    
    public class FruitRun {
        public static void main(String[] args) {
            FruitInfoUtil.getFruitInfo(Apple.class);
        }
    }

    输出:

     水果名称: Apple
     水果颜色: RED
    供应商编号: 1 供应商名称: 红富士 供应商地址: 上海
  • 相关阅读:
    Jenkins构建项目
    jenkins的理解及安装
    GitLab初识以及代码迁移
    深入浅出Git(偏向理论)
    理解下所谓的ssh隧道
    洛谷-P1908 逆序对
    洛谷-P1010 幂次方
    洛谷-P1226 【模板】快速幂||取余运算
    洛谷-P1074 靶形数独
    洛谷-P1433 吃奶酪
  • 原文地址:https://www.cnblogs.com/LoganChen/p/14140814.html
Copyright © 2011-2022 走看看