Created
May 23, 2024 08:57
-
-
Save hoho4190/fffb19abf5a918e71ed57ade8989192b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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