public static <T> Class<T> getActualTypeArguments(Class<?> clazz, int indexOfArgument) { Class<T> resolvedType = getActualTypeArguments(clazz.getSuperclass().getGenericSuperclass(), indexOfArgument); if (resolvedType == null) { return getActualTypeArguments(clazz.getGenericSuperclass(), indexOfArgument); } return resolvedType; }
public static Class<?> getGenericType(Field field) { return getGenericType(field, 0); }
static boolean hasEagerAnnotation(Field field) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { for (Annotation annotation : field.getAnnotations()) { if ((annotation instanceof OneToMany && isEagerFetch(annotation)) || annotation instanceof OneToOne) { return true; } } return false; }
public static <T> T initializeEagerAnnotatedFields(T instance) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IntrospectionException { Class<?> clazz = instance.getClass(); for (Field field : clazz.getDeclaredFields()) { if (hasEagerAnnotation(field)) { field.setAccessible(true); Object object = field.get(instance); if (object != null) { if (object instanceof Collection) { Collection collection = (Collection) object; for (Object elem : collection) { initializeEagerAnnotatedFields(elem); } } else { object = unproxyObject(object); if (object != null) { field.set(instance, object); initializeEagerAnnotatedFields(object); } } } } } return instance; }
@SuppressWarnings("unchecked") public static <T> void invokeSetter(Field field, Class<T> clazz, T targetObject, Object value) throws IntrospectionException, InvocationTargetException, IllegalAccessException, NoSuchMethodException { PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(), clazz); Method setter = descriptor.getWriteMethod(); if (setter != null) { Class<?> targetClass = setter.getParameterTypes()[0]; // do we need to convert the number type? if (value != null && Number.class.isAssignableFrom(targetClass)) { Number numValue = (Number) value; numValue = convertNumberType(numValue, (Class<? extends Number>) targetClass); setter.invoke(targetObject, numValue); } else { setter.invoke(targetObject, value); } } else { throw new NoSuchMethodException("No setter for " + descriptor.getDisplayName()); } }
protected BaseRepository() { entityType = Objects.requireNonNull(ReflectionUtil.<T>getActualTypeArguments(getClass(), 0)); }