How to use annotations to solve the problem that reflection does not guarantee the order of fields
This article focuses on "how to use annotations to solve the reflection does not guarantee the order of fields", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "how to use annotations to solve the reflection does not guarantee the order of fields"!
Talk is cheap, show me the code. Go straight to the code!
@ Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.FIELD) public @ interface MyColumn {int columnIndex () default 0 } public class PoiUtil {/ * get the file content list * * @ param file * @ param clazz * @ return * @ throws Exception * / public List getListFromFile (MultipartFile file, Class clazz) throws Exception {/ / finally return data List resultList = new ArrayList (); InputStream is = file.getInputStream () / / create using the factory method. Workbook wb = WorkbookFactory.create (is); Sheet sheet = wb.getSheetAt (0); int totalRowNum = sheet.getLastRowNum (); / / get the total number of columns int cellLength = sheet.getRow (0). GetPhysicalNumberOfCells (); / / get all the fields of the reflection class Field [] fields = clazz.getDeclaredFields (); / / create an array of fields that are in the same order as the excel rows. Field [] newFields = newField [cellLength]; for (int I = 0; I < cellLength; iTunes +) {for (Field field: fields) {Annotation [] annotationArr = field.getDeclaredAnnotations () For (Annotation annotation: annotationArr) {if (annotation instanceof MyColumn) {if (I = = ((MyColumn) annotation) .columnIndex ()) {newFields [I] = field } / / get for from line x (int x = 1; x ='A'& & str.charAt (0)