Commit 9a940a61 by zhangxingmin

push

parent 7ca1f888
...@@ -3,22 +3,29 @@ package com.yd.oss.service.service.impl; ...@@ -3,22 +3,29 @@ package com.yd.oss.service.service.impl;
import com.yd.oss.feign.annotation.PdfField; import com.yd.oss.feign.annotation.PdfField;
import com.yd.oss.service.service.FieldValueProvider; import com.yd.oss.service.service.FieldValueProvider;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Map;
/** /**
* 使用注解实现通用字段值提供器 * 支持注解和 Map 的通用字段值提供器
* @param <T>
*/ */
@Component @Component
public class AnnotationFieldValueProvider<T> implements FieldValueProvider<T> { public class AnnotationFieldValueProvider<T> implements FieldValueProvider<T> {
@Override @Override
@SuppressWarnings("unchecked")
public String getFieldValue(T object, String fieldName) { public String getFieldValue(T object, String fieldName) {
try { try {
// 获取所有字段 // 如果对象是 Map 类型
if (object instanceof Map) {
Map<String, Object> map = (Map<String, Object>) object;
Object value = map.get(fieldName);
return value != null ? value.toString() : "";
}
// 如果是普通 Java 对象,使用注解方式
Field[] fields = object.getClass().getDeclaredFields(); Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) { for (Field field : fields) {
PdfField annotation = field.getAnnotation(PdfField.class); PdfField annotation = field.getAnnotation(PdfField.class);
if (annotation != null && annotation.value().equals(fieldName)) { if (annotation != null && annotation.value().equals(fieldName)) {
...@@ -27,7 +34,7 @@ public class AnnotationFieldValueProvider<T> implements FieldValueProvider<T> { ...@@ -27,7 +34,7 @@ public class AnnotationFieldValueProvider<T> implements FieldValueProvider<T> {
return value != null ? value.toString() : ""; return value != null ? value.toString() : "";
} }
} }
// 如果没有找到注解,尝试使用字段名 // 如果没有找到注解,尝试使用字段名
try { try {
Field field = object.getClass().getDeclaredField(fieldName); Field field = object.getClass().getDeclaredField(fieldName);
...@@ -37,7 +44,7 @@ public class AnnotationFieldValueProvider<T> implements FieldValueProvider<T> { ...@@ -37,7 +44,7 @@ public class AnnotationFieldValueProvider<T> implements FieldValueProvider<T> {
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException e) {
return ""; return "";
} }
} catch (Exception e) { } catch (Exception e) {
return ""; return "";
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment