@Excel(name = “中文”)
public class I18nTest {
@Test
public void testSetExcelAnnotationValue() {
setExcelAnnotationValue(OperationLogExcelVo.class, "operatorName", "name");
}
@Test
public void testSetExcelAnnotationValues() {
LanguageUtils.setExcelAnnotationValues(OperationLogExcelVo.class, "name");
}
public static <T> void setExcelAnnotationValue(Class<T> ExcelClass, String fieldName, String key) {
try {
//获取OperationLogExcelVo的fieldName字段
Field field = ExcelClass.getDeclaredField(fieldName);
//获取val字段上的Excel注解实例
Excel excel = field.getAnnotation(Excel.class);
//获取 excel 这个代理实例所持有的 InvocationHandler
InvocationHandler invocationHandler = Proxy.getInvocationHandler(excel);
// 获取 AnnotationInvocationHandler 的 memberValues 字段
Field hField = invocationHandler.getClass().getDeclaredField("memberValues");
// 因为这个字段事 private final 修饰,所以要打开权限
hField.setAccessible(true);
// 获取 memberValues
Map memberValues = (Map) hField.get(invocationHandler);
String value = Optional.ofNullable(memberValues.get(key))
.map(Object::toString)
.map(LanguageUtils::getMessage)
.orElse(memberValues.get(key).toString());
memberValues.put(key, value);
System.out.println(excel.name());
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
}
public static <T> void setExcelAnnotationValues(Class<T> excelClass, String key) {
//获取OperationLogExcelVo的fieldName字段
Field[] declaredFields = excelClass.getDeclaredFields();
//获取val字段上的Excel注解实例
Arrays.stream(declaredFields)
.filter(field -> !field.getName().equalsIgnoreCase("serialVersionUID"))
.map(field -> field.getAnnotation(Excel.class))
.forEach(excel -> {
//获取 excel 这个代理实例所持有的 InvocationHandler
InvocationHandler invocationHandler = Proxy.getInvocationHandler(excel);
// 获取 AnnotationInvocationHandler 的 memberValues 字段
try {
Field hField = invocationHandler.getClass().getDeclaredField("memberValues");
// 因为这个字段事 private final 修饰,所以要打开权限
hField.setAccessible(true);
// 获取 memberValues
Map memberValues = (Map) hField.get(invocationHandler);
String value = Optional.ofNullable(memberValues.get(key))
.map(Object::toString)
.map(LanguageUtils::getMessage)
.orElse(memberValues.get(key).toString());
memberValues.put(key, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
});
}
}
public class OperationLogExcelVo extends LogicalDeleteEntity {
public OperationLogExcelVo() {
LanguageUtils.setExcelAnnotationValuesDef(this.getClass());
}
/**
* The constant serialVersionUID.
*/
private static final long serialVersionUID = 8122843270286604440L;
/**
* The Operator name.
*/
@Excel(name = "yhmdlm", orderNum = "1", width = 25)
private String operatorName;
}