Skip to content

Instantly share code, notes, and snippets.

@hoho4190
Created May 23, 2024 08:57
Show Gist options
  • Save hoho4190/fffb19abf5a918e71ed57ade8989192b to your computer and use it in GitHub Desktop.
Save hoho4190/fffb19abf5a918e71ed57ade8989192b to your computer and use it in GitHub Desktop.
package com...test;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.lang.reflect.Field;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ReflectionUtil {
public static void setFieldValue(Object object, String fieldName, Object valueTobeSet)
throws NoSuchFieldException, IllegalAccessException {
Field field = getField(object.getClass(), fieldName);
field.setAccessible(true);
field.set(object, valueTobeSet);
}
public static Object getPrivateFieldValue(Object object, String fieldName)
throws NoSuchFieldException, IllegalAccessException {
Field field = getField(object.getClass(), fieldName);
field.setAccessible(true);
return field.get(object);
}
private static <T> Field getField(Class<T> mClass, String fieldName)
throws NoSuchFieldException {
try {
return mClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
Class<?> superClass = mClass.getSuperclass();
if (superClass == null) {
throw e;
} else {
return getField(superClass, fieldName);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment