Add simple read/write methods

This commit is contained in:
Mark Vainomaa 2016-12-16 16:59:47 +02:00
parent 3b3e6e1bcf
commit 44ed555bf3
1 changed files with 39 additions and 0 deletions

View File

@ -121,4 +121,43 @@ public class Reflect {
field.set(instance, value);
} catch (IllegalAccessException e){}
}
/* Simpler reflection methods */
/**
* Read field
*
* @param instance Object where to read given field
* @param fieldName Field name
* @return Field contents or null
*/
@Nullable public static Object simpleReadField(@NotNull Object instance, @NotNull String fieldName){
try {
Field f = instance.getClass().getDeclaredField(fieldName);
if (!f.isAccessible()) {
f.setAccessible(true);
}
return f.get(instance);
} catch (NoSuchFieldException|IllegalAccessException e){
return null;
}
}
/**
* Write field
*
* @param instance Object where given field resides
* @param fieldName Field name
* @param value Field content
*/
public static void simpleWriteField(@NotNull Object instance, @NotNull String fieldName,
@Nullable Object value){
try {
Field f = instance.getClass().getDeclaredField(fieldName);
if (!f.isAccessible()) {
f.setAccessible(true);
}
f.set(instance, value);
} catch (NoSuchFieldException|IllegalAccessException ignored){}
}
}