aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/bartworks/util/CachedReflectionUtils.java
blob: a02b644b4a0710166300283a3087c7426808c2b5 (plain)
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
package bartworks.util;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.reflect.FieldUtils;

public class CachedReflectionUtils {

    private static final ClassValue<Map<String, Field>> fields = new ConcurrentMapClassValue();
    private static final ClassValue<Map<String, Field>> declaredFields = new ConcurrentMapClassValue();

    public static Field getField(final Class<?> cls, final String fieldName) {
        return fields.get(cls)
            .computeIfAbsent(fieldName, f -> FieldUtils.getField(cls, f, true));
    }

    public static Field getDeclaredField(final Class<?> cls, final String fieldName) {
        return declaredFields.get(cls)
            .computeIfAbsent(fieldName, f -> FieldUtils.getDeclaredField(cls, f, true));
    }

    private static class ConcurrentMapClassValue extends ClassValue<Map<String, Field>> {

        @Override
        protected Map<String, Field> computeValue(Class<?> type) {
            return new ConcurrentHashMap<>();
        }
    }
}