yangys
2024-04-04 2cf2921440e7473ae50796c2cb688f609b3a7995
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.qianwen.core.tool.convert;
 
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.qianwen.core.tool.function.CheckedFunction;
import com.qianwen.core.tool.utils.ClassUtil;
import com.qianwen.core.tool.utils.ConvertUtil;
import com.qianwen.core.tool.utils.ReflectUtil;
import com.qianwen.core.tool.utils.Unchecked;
import org.springframework.cglib.core.Converter;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.lang.Nullable;
 
/* loaded from: blade-core-tool-9.3.0.0-SNAPSHOT.jar:org/springblade/core/tool/convert/BladeConverter.class */
public class BladeConverter implements Converter {
    private static final Logger log = LoggerFactory.getLogger(BladeConverter.class);
    private static final ConcurrentMap<String, TypeDescriptor> TYPE_CACHE = new ConcurrentHashMap();
    private final Class<?> sourceClazz;
    private final Class<?> targetClazz;
 
    public BladeConverter(final Class<?> sourceClazz, final Class<?> targetClazz) {
        this.sourceClazz = sourceClazz;
        this.targetClazz = targetClazz;
    }
 
    @Nullable
    public Object convert(Object value, Class target, final Object fieldName) {
        if (value == null) {
            return null;
        }
        if (ClassUtil.isAssignableValue(target, value)) {
            return value;
        }
        try {
            TypeDescriptor targetDescriptor = getTypeDescriptor(this.targetClazz, (String) fieldName);
            if (Map.class.isAssignableFrom(this.sourceClazz)) {
                return ConvertUtil.convert(value, targetDescriptor);
            }
            TypeDescriptor sourceDescriptor = getTypeDescriptor(this.sourceClazz, (String) fieldName);
            return ConvertUtil.convert(value, sourceDescriptor, targetDescriptor);
        } catch (Throwable e) {
            log.warn("BladeConverter error", e);
            return null;
        }
    }
 
    private static TypeDescriptor getTypeDescriptor(final Class<?> clazz, final String fieldName) {
        String srcCacheKey = clazz.getName() + fieldName;
        CheckedFunction<String, TypeDescriptor> uncheckedFunction = key -> {
            Field field = ReflectUtil.getField(clazz, fieldName);
            if (field == null) {
                throw new NoSuchFieldException(fieldName);
            }
            return new TypeDescriptor(field);
        };
        return TYPE_CACHE.computeIfAbsent(srcCacheKey, Unchecked.function(uncheckedFunction));
    }
}