Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use annotations to solve the problem that reflection does not guarantee the order of fields

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report