Created
February 4, 2016 06:17
-
-
Save Pooh3Mobi/8dda3eb3efbb93c08809 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
public class ReflectionUtil { | |
public static Object getField(Object object, String strName) throws NoSuchFieldException, IllegalAccessException { | |
if(object == null || object.getClass() == null) return null; | |
Field field = object.getClass().getField(strName); | |
return field.get(object); | |
} | |
public static Object getDeclaredField(Object obj, String name) | |
throws SecurityException, NoSuchFieldException, | |
IllegalArgumentException, IllegalAccessException { | |
Field f = obj.getClass().getDeclaredField(name); | |
f.setAccessible(true); | |
return f.get(obj); | |
} | |
public static void setValueToDeclaredField(Object obj, String name, Object value) | |
throws SecurityException, NoSuchFieldException, | |
IllegalArgumentException, IllegalAccessException { | |
Field f = obj.getClass().getDeclaredField(name); | |
f.setAccessible(true); | |
f.set(obj, value); | |
} | |
public static void setValueToDeclaredFieldFromSuperClass(Object obj, String name, Object value) | |
throws SecurityException, NoSuchFieldException, | |
IllegalArgumentException, IllegalAccessException { | |
Field f = getFieldFromSuperClass(obj.getClass(), name); | |
f.setAccessible(true); | |
f.set(obj, value); | |
} | |
public static Field getFieldFromSuperClass(Class clazz, String fieldName) | |
throws NoSuchFieldException { | |
Field field = null; | |
while (clazz != null) { | |
try { | |
field = clazz.getDeclaredField(fieldName); | |
break; | |
} catch (NoSuchFieldException e) { | |
clazz = clazz.getSuperclass(); | |
} | |
} | |
if (field == null) { | |
throw new NoSuchFieldException(); | |
} | |
return field; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment