Comprender la anotación tres de Java

Bueno, la comprensión previa de la anotación java dos , la comprensión de la anotación java uno, ya ha hablado sobre algunos conocimientos básicos de la anotación java, echemos un vistazo a la aplicación específica.

Las explicaciones anteriores son relativamente sencillas y muchos socios se sentirán un poco insatisfechos después de leerlas. ¿Qué estás escribiendo? Es casi como si no hubiera nada escrito, ¡nada seco! Sin embargo, lo que escribí antes eran aplicaciones muy simples, y cualquiera que haya leído una pequeña anotación de Java puede hacerlo.

De hecho, muchos socios sienten que las anotaciones son mágicas y quieren entenderlas, pero no saben por dónde empezar. Las anotaciones parecen misteriosas, complicadas y difíciles de usar. Por ejemplo: al ver que un colega agrega una anotación en la clase, método o atributo, puede verificar permisos, verificar parámetros e incluso procesar atributos. De repente, es tan alto y alto en la nube.! De hecho, si corta con cuidado el velo de la anotación, ¡encontrará que no es demasiado profundo!

A continuación, hablaré sobre el uso de anotaciones cuando se encapsulan objetos especiales de forma unificada.

Primero, cree una anotación para identificar que este objeto tiene adjuntos, y necesita hacer recursivamente (profundizar) para obtener el objeto adjunto (iniciar código de agua).

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AttachAnnotion {

}

Luego, vaya directamente al tema y cree un objeto adjunto AttachInfoList para identificar un lugar para cargar adjuntos, que contiene refId y la colección de adjuntos attachInfos:

@Data
public class AttachInfoList extends BaseVO{

    private String refId ;

    private List<AttachVO> attachVOList;
}

Cree un objeto de página PageTestVO a continuación

@Data
public class PageTestVO extends BaseVO {

    private String pageName;

    @AttachAnnotion
    private ParagraphVO paragraphVO;

    //单个文件
    private AttachInfoList attachInfo;

    //多个文件
    private List<AttachInfoList> attachInfos;

    private String imageRefId;

}

Entre ellos, el párrafo VO es un párrafo, que también contiene información del archivo.

@Data
public class ParagraphVO extends BaseVO {

    private String name ;

    /**
     * 附件
     */
    private AttachInfoList attachInfoLists;
    
}

Una vez creado el objeto, el problema se manejará mediante la reflexión y la anotación a continuación. El código se ha anotado con más detalle. Veámoslo ~

package com.example.demo;

import com.alibaba.fastjson.JSON;

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

public class AnnoTest {
    public static void main(String[] args) {
        PageTestVO base = new PageTestVO();
        List<AttachInfoList> attachInfos = new ArrayList<>();

        // 单个--- attachInfo
        AttachInfoList attachInfo = new AttachInfoList();
        AttachVO test111 = new AttachVO("111", "test111");
        List<AttachVO> list1 = new ArrayList<>();
        list1.add(test111);
        attachInfo.setAttachVOList(list1);
        attachInfo.setRefId("test111");
        base.setAttachInfo(attachInfo);

        //多个 ----- attachInfos
        AttachInfoList attachInfo2 = new AttachInfoList();
        AttachVO test222 = new AttachVO("222", "test222");
        List<AttachVO> list2 = new ArrayList<>();
        list2.add(test222);
        attachInfo2.setAttachVOList(list2);

        AttachInfoList attachInfo3 = new AttachInfoList();
        AttachVO test333 = new AttachVO("333", "test333");
        List<AttachVO> list3 = new ArrayList<>();
        list3.add(test333);
        attachInfo3.setAttachVOList(list3);

        List<AttachInfoList> attachInfoLists23 = new ArrayList<>();
        attachInfoLists23.add(attachInfo2);
        attachInfoLists23.add(attachInfo3);
        base.setAttachInfos(attachInfoLists23);

        //注解嵌套 -----paragraphVO
        AttachInfoList attachInfo4 = new AttachInfoList();
        AttachVO test444 = new AttachVO("444", "test444");
        List<AttachVO> list4 = new ArrayList<>();
        list4.add(test444);
        attachInfo4.setAttachVOList(list4);
        ParagraphVO paragraphVO = new ParagraphVO();
        paragraphVO.setAttachInfoLists(attachInfo4);
        base.setParagraphVO(paragraphVO);

        dealAttachInfo(base, attachInfos);

        System.out.println("数据附件提取:" + JSON.toJSON(attachInfos));
    }
    
    public static <T> void dealAttachInfo(T base, List<AttachInfoList> attachInfos) {
        // 为空不处理
        if (base == null) {
            return;
        }
        // 对象是AttachInfoList,直接处理
        if (base instanceof AttachInfoList) {
            attachInfos.add((AttachInfoList) base);
            return;
        }
        // 集合遍历处理
        if (base instanceof List) {
            Iterator it = ((List) base).iterator();
            while (it.hasNext()) {
                dealAttachInfo(it.next(), attachInfos);
            }
        } else {
            //处理逻辑
            Class<?> baseClass = base.getClass();
            //遍历属性处理
            Field[] fields = baseClass.getDeclaredFields();
            try {
                for (Field field : fields) {
                    String name = field.getName(); //属性名称
                    String getMethodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1); //获取该属性的方法名
                    Method method = baseClass.getMethod(getMethodName);  //获取该属性的方法
                    Object obj = method.invoke(base);   //该属性类型及值
                    //这个属性是AttachInfoList,那么直接封装禁attachInfos
                    if (obj == null) continue;
                    if (obj instanceof AttachInfoList) {
                        attachInfos.add((AttachInfoList) obj);
                    } else if (obj instanceof List && ((List) obj).size() > 0 && ((List) obj).get(0) instanceof AttachInfoList) {
                        attachInfos.addAll((List) obj);
                    } else {
                        //如果不是,继续查找注解,看看是否需要继续下钻
                        AttachAnnotion attachAnnotion = field.getDeclaredAnnotation(AttachAnnotion.class);  //是否有文件注解
                        if (attachAnnotion != null) {
                            if (obj instanceof List) {
                                for (Object ob : (List) obj) {
                                    dealAttachInfo(ob, attachInfos);
                                }
                            } else {
                                dealAttachInfo(obj, attachInfos);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println("出现错误:" + e.getMessage() + "   location:" + e.getLocalizedMessage());
            }
        }
    }
}

Deje que todos vean los resultados de la operación:

com.example.demo.AnnoTest
数据附件提取:[{"attachVOList":[{"name":"test444","attachId":"444"}]},{"refId":"test111","attachVOList":[{"name":"test111","attachId":"111"}]},{"attachVOList":[{"name":"test222","attachId":"222"}]},{"attachVOList":[{"name":"test333","attachId":"333"}]}]

Copié todo el código directamente, aquí quiero decir algunos puntos: 1. Me ocupo de esta lógica complicada, de hecho, esto no aparecerá:

   //多个文件
    private List<AttachInfoList> attachInfos;

Debido a que AttachInfoList en sí mismo es una colección de adjuntos, que tiene un ID asociado, si hay más de uno, obviamente es necesario crear múltiples AttachInfoLists en lugar de recopilarlos juntos nuevamente. Algunas cosas en el código se pueden eliminar, por supuesto, no habrá problemas si no lo resuelve, pero la lógica no desaparece.

2. Algunos socios se enteraron, ¿eh? No uso anotaciones, ¡solo uso la reflexión para hacerlo! ¡Así es! Sí, puede recurrir capa por capa sin usar anotaciones para obtener la información del archivo adjunto, pero debido a que no hay una marca de anotación, recurrirá a cada objeto, independientemente de si el objeto tiene un archivo o no, lo que no es muy amigable para el rendimiento. Incluso si el costo de rendimiento no es mucho.

3. En realidad, esto es solo extraer los archivos adjuntos. Si desea guardar, debe ensamblar el procesamiento de datos. Preste atención a la creación de asociaciones refId, etc. Al mismo tiempo, parece que también puede procesar archivos en lotes cuando consultas. Los amigos interesados ​​pueden intentarlo.

Supongo que te gusta

Origin blog.csdn.net/zsah2011/article/details/105475075
Recomendado
Clasificación