ReflectionUtils.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package me.lortseam.completeconfig.util;
  2. import com.google.common.reflect.TypeToken;
  3. import io.leangen.geantyref.GenericTypeReflector;
  4. import lombok.experimental.UtilityClass;
  5. import org.apache.commons.lang3.StringUtils;
  6. import java.lang.reflect.*;
  7. import java.util.Optional;
  8. @UtilityClass
  9. public final class ReflectionUtils {
  10. public static Class<?> getTypeClass(Type type) {
  11. return TypeToken.of(type).getRawType();
  12. }
  13. public static Type getFieldType(Field field) {
  14. return GenericTypeReflector.getExactFieldType(field, field.getDeclaringClass());
  15. }
  16. public static <T> T instantiateClass(Class<T> clazz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
  17. Constructor<T> constructor = clazz.getDeclaredConstructor();
  18. if (!constructor.canAccess(null)) {
  19. constructor.setAccessible(true);
  20. }
  21. return constructor.newInstance();
  22. }
  23. public static Optional<Method> getSetterMethod(Field field, Object object) {
  24. Method method;
  25. try {
  26. method = field.getDeclaringClass().getDeclaredMethod("set" + StringUtils.capitalize(field.getName()), getTypeClass(getFieldType(field)));
  27. } catch (NoSuchMethodException ignore) {
  28. return Optional.empty();
  29. }
  30. if (Modifier.isStatic(field.getModifiers()) != Modifier.isStatic(method.getModifiers()) || !method.getReturnType().equals(Void.TYPE)) {
  31. return Optional.empty();
  32. }
  33. if (!method.canAccess(object)) {
  34. method.setAccessible(true);
  35. }
  36. return Optional.of(method);
  37. }
  38. public static Type boxType(Type type) {
  39. return GenericTypeReflector.box(type);
  40. }
  41. }