1 package com.irtimaled.bbor.common;
3 import java.lang.reflect.Field;
4 import java.lang.reflect.ParameterizedType;
5 import java.lang.reflect.Type;
6 import java.util.function.Function;
8 public class ReflectionHelper {
9 public static <T, R> Function<T, R> getPrivateFieldGetter(Class<?> clazz, Type fieldType, Type... genericTypeArguments) {
10 Field field = findField(clazz, fieldType, genericTypeArguments);
11 if (field == null) return obj -> null;
13 field.setAccessible(true);
16 return (R) field.get(obj);
17 } catch (IllegalAccessException ignored) {
23 private static Field findField(Class<?> clazz, Type fieldType, Type[] genericTypeArguments) {
24 for (Field field : clazz.getDeclaredFields()) {
25 Type type = field.getGenericType();
26 ParameterizedType genericType = TypeHelper.as(type, ParameterizedType.class);
27 if (genericType == null) {
28 if (type != fieldType || genericTypeArguments.length > 0) continue;
32 Type rawType = genericType.getRawType();
33 if (rawType != fieldType) continue;
35 Type[] actualTypeArguments = genericType.getActualTypeArguments();
36 if (!typesMatch(genericTypeArguments, actualTypeArguments)) continue;
43 private static boolean typesMatch(Type[] left, Type[] right) {
44 if (left.length != right.length) return false;
46 for (int index = 0; index < right.length; index++) {
47 if (right[index] != left[index]) {