Understanding java annotation three

Well, the previous understanding of java annotation two , understanding of java annotation one, has already talked about some basic knowledge of java annotation, let's take a look at the specific application.

The previous explanations are relatively simple, and many partners will be a little dissatisfied after reading them. What are you writing? It’s almost the same as not written, nothing dry! However, what I wrote before were very simple applications, and anyone who has read a little java annotation can make it.

In fact, many partners feel that annotations are magical and want to understand them, but they don't know where to start. The annotations look so mysterious, complicated, and difficult to use. For example: Seeing that a colleague adds an annotation on the class, method or attribute, you can verify permissions, verify parameters, and even process attributes. At a sudden glance, it is so tall and tall in the cloud. ! In fact, if you carefully cut the veil of the annotation, you will find that this is not too deep!

Next, I will talk about the use of annotations when special objects are encapsulated in a unified way.

First, create an annotation to identify that this object has attachments, and you need to recursively (drill down) to get the attachment object (start water code).

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

}

Then go directly to the topic and create an attachment object AttachInfoList to identify a place to upload attachments, which contains refId and attachments collection attachInfos:

@Data
public class AttachInfoList extends BaseVO{

    private String refId ;

    private List<AttachVO> attachVOList;
}

Create a page object PageTestVO below

@Data
public class PageTestVO extends BaseVO {

    private String pageName;

    @AttachAnnotion
    private ParagraphVO paragraphVO;

    //单个文件
    private AttachInfoList attachInfo;

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

    private String imageRefId;

}

Among them paragraphVO is a paragraph, which also contains file information

@Data
public class ParagraphVO extends BaseVO {

    private String name ;

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

After the object is created, the problem will be handled through reflection and annotation below. The code has been annotated in more detail. Let's look at it~

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());
            }
        }
    }
}

Let everyone see the results of the operation:

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"}]}]

I copied all the code directly, here I want to say a few points: 1. I deal with this logic complicated, in fact, this will not appear:

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

Because AttachInfoList itself is a collection of attachments, which has an associated id, if there are more than one, it is obvious that multiple AttachInfoLists need to be created instead of being assembled together again. Some things in the code can be deleted, and of course there will be no problems if they are not processed, but the logic will not go away.

2. Some partners found out, hey? I don't use annotations, just use reflection to get it done! That's right! Yes, you can recurse layer by layer without using annotations to get the attachment information, but because there is no annotation mark, you will recurse each object, regardless of whether the object has a file or not, which is not very friendly to performance , Even if the performance cost is not much.

3. This is actually just extracting the attachments. If you want to save, you need to assemble data processing. Pay attention to the creation of refId associations, etc. At the same time, it seems that you can also process files in batches when querying. Interested friends can try .

Guess you like

Origin blog.csdn.net/zsah2011/article/details/105475075