Last active
June 15, 2016 13:56
-
-
Save ultraon/9e52e175cfa050b80bfa0296f9fe02b5 to your computer and use it in GitHub Desktop.
The reflection utils for convenient working with java reflection operations
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 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