Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The reflection utils for convenient working with java reflection operations
package utils;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.lang.reflect.Field;
/**
* The utility class with reflection convenient methods.
*/
public class ReflectionUtils {
/**
* Set the new value for the field in the object.
*
* @param object the target object with some field
* @param fieldName the name of the target field in the target object
* @param value the new value for the target field
* @return true if the process was successful, otherwise false
*/
public static boolean setProperty(Object object, String fieldName, Object value) {
final Field valueField = lookupField(object.getClass(), fieldName);
if (null != valueField) {
valueField.setAccessible(true);
try {
valueField.set(object, value);
} catch (IllegalAccessException e) {
return false;
}
return true;
}
return false;
}
/**
* Lookup the field with name in all class hierarchy (private/package-private/protected/public).
*
* @param clazz the target {@link Class}
* @param fieldName the name of the field
* @return the {@link Field} or null
*/
@Nullable
public static Field lookupField(@NonNull final Class<?> clazz, @NonNull final String fieldName) {
Field declaredField;
try {
declaredField = clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException ignored) {
final Class<?> superclass = clazz.getSuperclass();
if (null == superclass) {
return null;
}
declaredField = lookupField(superclass, fieldName);
}
return declaredField;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.