Java custom annotation usage

Posted by doug007 on Fri, 08 Nov 2019 16:55:41 +0100

 

First, explain

1. Definition of notes

The Java file is called Annotation, which is represented by @ interface.

2. yuan annotation

There are some notes on @ interface as needed, including @ Retention, @ Target, @ Document, @ Inherited.

3. Retention policy of notes

@ Retention(RetentionPolicy.SOURCE) / / the annotation only exists in the source code, not in the class bytecode file

@ Retention(RetentionPolicy.CLASS) / / the default retention policy. The annotation will exist in the class bytecode file, but cannot be obtained at runtime

@ Retention(RetentionPolicy.RUNTIME) / / the annotation will exist in the class bytecode file. It can be obtained by reflection at runtime

4. Purpose of annotation

@ Target(ElementType.TYPE) interface, class, enumeration, annotation

@ Target(ElementType.FIELD), enumeration constant

@ Target(ElementType.METHOD) method

@ Target(ElementType.PARAMETER) / / - method parameter

@ Target(ElementType.CONSTRUCTOR) / / - constructor

@ target (ElementType. Local? Variable) / / local variable

@ target (ElementType. Annotation? Type) / /

@ Target(ElementType.PACKAGE)

5. Annotations are included in javadoc

  @Documented

6. Annotations can be inherited

  @Inherited

7. Annotation parser

Used to parse custom annotations.

Two, usage

1. Customize a note

package com.dhcc.demo.domain.poi;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelAttribute {
    /** Corresponding column name */
    String name() default "";

    /** excel Column index */
    int sort();

    /** Format corresponding to field type */
    String format() default "";
}

2. Only annotation is used in the model

package com.dhcc.demo.domain;

import com.dhcc.demo.domain.poi.ExcelAttribute;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * User entity class
 */
@Entity
@Table(name = "t_user")
@Getter
@Setter
@NoArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = 4297464181093070302L;
    /**
     * ID
     */
    @Id
    private String id;
    /**
     * Phone number
     */
    @ExcelAttribute(sort = 2)
    private String mobile;
    /**
     * User name
     */
    @ExcelAttribute(sort = 1)
    private String username;

    ...
}

3. Runtime parsing comments

package com.dhcc.demo.common.poi;


import com.dhcc.demo.domain.poi.ExcelAttribute;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.format.CellFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class ExcelImportUtil<T> {
 
    private Class clazz;
    private  Field fields[];
 
    public ExcelImportUtil(Class clazz) {
        this.clazz = clazz;
        fields = clazz.getDeclaredFields();
    }
 
    /**
     * Reading excel based on annotation
     */
    public List<T> readExcel(InputStream is, int rowIndex,int cellIndex) {
        List<T> list = new ArrayList<T>();
        T entity = null;
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            Sheet sheet = workbook.getSheetAt(0);
            // Inaccurate
            int rowLength = sheet.getLastRowNum();

            System.out.println(sheet.getLastRowNum());
            for (int rowNum = rowIndex; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                entity = (T) clazz.newInstance();
                System.out.println(row.getLastCellNum());
                for (int j = cellIndex; j < row.getLastCellNum(); j++) {
                    Cell cell = row.getCell(j);
                    for (Field field : fields) {
                        if(field.isAnnotationPresent(ExcelAttribute.class)){
                            field.setAccessible(true);
                            ExcelAttribute ea = field.getAnnotation(ExcelAttribute.class);
                            if(j == ea.sort()) {
                                field.set(entity, covertAttrType(field, cell));
                            }
                        }
                    }
                }
                list.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
 

    /**
     * Type conversion converts cell cell format to field type
     */
    private Object covertAttrType(Field field, Cell cell) throws Exception {
        String fieldType = field.getType().getSimpleName();
        if ("String".equals(fieldType)) {
            return getValue(cell);
        }else if ("Date".equals(fieldType)) {
            return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(getValue(cell)) ;
        }else if ("int".equals(fieldType) || "Integer".equals(fieldType)) {
            return Integer.parseInt(getValue(cell));
        }else if ("double".equals(fieldType) || "Double".equals(fieldType)) {
            return Double.parseDouble(getValue(cell));
        }else {
            return null;
        }
    }
 
 
    /**
     * Format to String
     * @param cell
     * @return
     */
    public String getValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getRichStringCellValue().getString().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    Date dt = DateUtil.getJavaDate(cell.getNumericCellValue());
                    return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(dt);
                } else {
                    // Prevent numerical value from becoming scientific counting method
                    String strCell = "";
                    Double num = cell.getNumericCellValue();
                    BigDecimal bd = new BigDecimal(num.toString());
                    if (bd != null) {
                        strCell = bd.toPlainString();
                    }
                    // Remove floating point auto add. 0
                    if (strCell.endsWith(".0")) {
                        strCell = strCell.substring(0, strCell.indexOf("."));
                    }
                    return strCell;
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return "";
        }
    }
}

 

 

Topics: Java Apache Lombok Excel