手动添加很麻烦,有什么好的方法吗
时间: 2024-03-26 17:40:16 浏览: 23
可以使用 Java 语言提供的反射机制来实现自动为属性添加 `orderNum` 属性,并自动递增赋值。具体实现可以参考下面的代码:
```java
import java.lang.reflect.Field;
public class ExcelFieldOrderHelper {
private static int orderNum = 10;
public static void setExcelFieldOrder(Object obj) {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
Excel excel = field.getAnnotation(Excel.class);
if (excel != null) {
try {
String fieldName = field.getName();
field.setAccessible(true);
Object value = field.get(obj);
field.set(obj, value);
field.setAccessible(false);
Field orderField = excel.getClass().getDeclaredField("orderNum");
orderField.setAccessible(true);
orderField.set(excel, String.valueOf(orderNum++));
orderField.setAccessible(false);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
```
然后在需要自动添加 `orderNum` 属性的类中,可以在构造方法或者其他初始化方法中调用该工具类的 `setExcelFieldOrder` 方法,例如:
```java
public class MyClass {
@Excel(name = "负荷率", groupName = "萨南深冷", fixedIndex = 10)
private String snslfhl;
@Excel(name = "外输气阀组压力", groupName = "萨南深冷", fixedIndex = 11)
private String snslwsqfyl;
// 其他属性...
public MyClass() {
ExcelFieldOrderHelper.setExcelFieldOrder(this);
}
}
```
这样在创建 `MyClass` 的实例时,就会自动为类中所有添加了 `@Excel` 注解的属性添加 `orderNum` 属性,并自动递增赋值。