反射+自定义注解,实现获取注解标记的属性 注解Annotation实现原理与自定义注解例子 https://www.cnblogs.com/acm-bingzi/p/javaAnnotation.html

寻技术 Html/CSS / JAVA编程 2023年07月16日 145

目标:通过自定义注解 @Ignore 注解,觉得是否读取指定类的属性。

自定义注解:基础详见  注解Annotation实现原理与自定义注解例子

 

运行结果:

[main] INFO  util.FruitInfoUtil  - 水果的名字为:entity.Apple
[main] INFO  util.FruitInfoUtil  - 水果的颜色为:RED
[main] INFO  util.FruitInfoUtil  - 水果的供应商名称为:红富士供应商,供应商地址为:山西红富士产业园
[main] INFO  main.MainTest  - ====================
[main] INFO  util.FieldsUtil  - fieldName:fruitColor's ignore is null
[main] INFO  util.FieldsUtil  - fieldName:fruitProvider's ignore is false
[main] INFO  util.FieldsUtil  - fields: [main] INFO util.FieldsUtil - fruitColor [main] INFO util.FieldsUtil - fruitProvider [main] INFO util.FieldsUtil - END

 

import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitName {
    String value() default "";
}

  

import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitColor {
    public enum  Color {GREND, RED, BLUE}

    Color fruitColor() default Color.GREND;
}

  

import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitProvider {
    int id() default -1;

    String name() default "";

    String addr() default "";
}

  

import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Ignore {
    boolean ignore() default false;
}

  

import annotation.FruitColor;
import annotation.FruitName;
import annotation.FruitProvider;
import annotation.Ignore;

public class Apple {
    @FruitName("entity.Apple")
    @Ignore(ignore = true)
    String fruitName;
    @FruitColor(fruitColor = FruitColor.Color.RED)
//    @Ignore(ignore = true)
    String fruitColor;
    @FruitProvider(id = 1, name = "红富士供应商", addr = "山西红富士产业园")
    @Ignore
    String fruitProvider;

    public String getFruitName() {
        return fruitName;
    }

    public void setFruitName(String fruitName) {
        this.fruitName = fruitName;
    }

    public String getFruitColor() {
        return fruitColor;
    }

    public void setFruitColor(String fruitColor) {
        this.fruitColor = fruitColor;
    }

    public String getFruitProvider() {
        return fruitProvider;
    }

    public void setFruitProvider(String fruitProvider) {
        this.fruitProvider = fruitProvider;
    }

    public void getAppleName(){
        System.out.println("水果的名称为:苹果。");
    }
}

  

import annotation.FruitColor;
import annotation.FruitName;
import annotation.FruitProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

public class FruitInfoUtil {
    final static Logger logger = LoggerFactory.getLogger(FruitInfoUtil.class);
    public static void getAnnotationInfo(Class clazz){
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if(field.isAnnotationPresent(FruitName.class)){
                FruitName fruitName = field.getAnnotation(FruitName.class);
                logger.info("水果的名字为:"+fruitName.value());
            }
            else if(field.isAnnotationPresent(FruitColor.class)) {
                FruitColor fruitColor = field.getAnnotation(FruitColor.class);
                logger.info("水果的颜色为:" + fruitColor.fruitColor());
            }
            else if(field.isAnnotationPresent(FruitProvider.class)){
                FruitProvider fruitProvider = field.getAnnotation(FruitProvider.class);
                logger.info("水果的供应商名称为:" + fruitProvider.name()+",供应商地址为:"+fruitProvider.addr());
            }
        }
    }
}

  

import annotation.Ignore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class FieldsUtil {
    final static Logger logger = LoggerFactory.getLogger(FieldsUtil.class);

    /**
     * 本类的所有 Ignore = false的字段集合
     * @param clazz
     */
    public static void getOneSelfActiveFieldsUtil(Class clazz){
        Field[] fields = clazz.getDeclaredFields();
        List<String> fileNames = new ArrayList<>();
        for (Field field : fields){
            String fieldName = field.getName();
            Ignore ignoreField = field.getAnnotation(Ignore.class);
            if(field.isAnnotationPresent(Ignore.class) && !ignoreField.ignore()){
                fileNames.add(field.getName());
                logger.info("fieldName:"+fieldName+"'s ignore is false");
            }
            else if(!field.isAnnotationPresent(Ignore.class)){
                fileNames.add(field.getName());
                logger.info("fieldName:"+fieldName+"'s ignore is null");
            }
        }

        logger.info("fields:");
        if(fileNames != null && fileNames.size() > 0){
//            fileNames.stream().forEach(System.out::println);
            fileNames.stream().forEach(y -> {
                logger.info(y);
            });
        }else{
            logger.info("Size() == 0 ");
        }
        logger.info("END");
    }

    /**
     * 包括 父类的所有Ignore = false(默认值)的字段信息
     * @param clazz
     */
    public static List<Field> getAllActiveFieldsUtil(Class clazz){
        List<String> fileNames = new ArrayList<>();
        List<Field> fieldList = null;
        Field[] fields;
        do{
            fields = clazz.getDeclaredFields();

            if(fields != null && fields.length > 0){
                for (Field field : fields){
                    String fieldName = field.getName();
                    Ignore ignoreField = field.getAnnotation(Ignore.class);
                    if(field.isAnnotationPresent(Ignore.class) && !ignoreField.ignore()){
                        fileNames.add(field.getName());
                        logger.info("fieldName:"+fieldName+"'s ignore is false");
                        fieldList.add(field);
                    }
                    else if(!field.isAnnotationPresent(Ignore.class)){
                        fileNames.add(field.getName());
                        logger.info("fieldName:"+fieldName+"'s ignore is null");
                        fieldList.add(field);
                    }
                }
                if(fileNames != null && fileNames.size() > 0){
                    fileNames.stream().forEach(System.out::println);
                }else{
                    logger.info("Size() == 0 ");
                }
                logger.info("END");
            }
            clazz = clazz.getSuperclass();
        }while (clazz != Object.class && clazz != null);
        return fieldList;
    }


}

  

import entity.Apple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.FieldsUtil;
import util.FruitInfoUtil;

public class MainTest {
    final static Logger logger = LoggerFactory.getLogger(MainTest.class);
    public static void main(String[] args) {
        FruitInfoUtil.getAnnotationInfo(Apple.class);
        logger.info("====================");
        FieldsUtil.getOneSelfActiveFieldsUtil(Apple.class);
    }
}

  

参考资源:

https://www.cnblogs.com/acm-bingzi/p/javaAnnotation.html

关闭

用微信“扫一扫”