编程语言
首页 > 编程语言> > Java自己写一个注解

Java自己写一个注解

作者:互联网

看如下代码:

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 供应商名称: 红富士 供应商地址: 上海

 

标签:Java,String,package,AnnotationTest,自己,public,field,注解,class
来源: https://www.cnblogs.com/LoganChen/p/14140814.html