Skip to content

Instantly share code, notes, and snippets.

@ultraon
Last active June 15, 2016 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ultraon/9e52e175cfa050b80bfa0296f9fe02b5 to your computer and use it in GitHub Desktop.
Save ultraon/9e52e175cfa050b80bfa0296f9fe02b5 to your computer and use it in GitHub Desktop.
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