1 package com.irtimaled.bbor.common;
3 import java.lang.reflect.Constructor;
4 import java.lang.reflect.Field;
5 import java.lang.reflect.ParameterizedType;
6 import java.lang.reflect.Type;
7 import java.util.function.Function;
9 public class ReflectionHelper {
10 public static <T, R> Function<T, R> getPrivateFieldGetter(Class<?> clazz, Type fieldType, Type... genericTypeArguments) {
11 Field field = findField(clazz, fieldType, genericTypeArguments);
12 if (field == null) return obj -> null;
14 field.setAccessible(true);
17 return (R) field.get(obj);
18 } catch (IllegalAccessException ignored) {
24 private static Field findField(Class<?> clazz, Type fieldType, Type[] genericTypeArguments) {
25 for (Field field : clazz.getDeclaredFields()) {
26 Type type = field.getGenericType();
27 ParameterizedType genericType = TypeHelper.as(type, ParameterizedType.class);
28 if (genericType == null) {
29 if (type != fieldType || genericTypeArguments.length > 0) continue;
33 Type rawType = genericType.getRawType();
34 if (rawType != fieldType) continue;
36 Type[] actualTypeArguments = genericType.getActualTypeArguments();
37 if (!typesMatch(genericTypeArguments, actualTypeArguments)) continue;
44 private static boolean typesMatch(Type[] left, Type[] right) {
45 if (left.length != right.length) return false;
47 for (int index = 0; index < right.length; index++) {
48 if (right[index] != left[index]) {
55 public static <T, R> Function<T, R> getPrivateInstanceBuilder(Class<R> clazz, Class<T> parameter) {
56 Constructor<R> constructor = findConstructor(clazz, parameter);
57 if (constructor == null) return obj -> null;
59 constructor.setAccessible(true);
62 return (R) constructor.newInstance(obj);
63 } catch (Exception ignored) {
69 private static <T> Constructor<T> findConstructor(Class<T> clazz, Class<?>... parameters) {
71 return clazz.getDeclaredConstructor(parameters);
72 } catch (NoSuchMethodException ignored) {