Skip to content

Instantly share code, notes, and snippets.

@Sythelux
Created September 12, 2014 13:08
Show Gist options
  • Save Sythelux/9bff4fde7395abad5ec7 to your computer and use it in GitHub Desktop.
Save Sythelux/9bff4fde7395abad5ec7 to your computer and use it in GitHub Desktop.
Abstract Access
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class TestFieldHandling {
private int Field1;
private String Field2;
@Override
public String toString() {
return Field1 + Field2;
}
public static void main(String[] args) {
Map<String, Object> m = new HashMap<>();
m.put("Field1", 20);
m.put("Field2", "Euro");
TestFieldHandling tfh = test(TestFieldHandling.class, m);
System.out.println(tfh.toString());
}
private static <T> T test(Class<T> tfhc, Map<String, Object> params) {
try {
T o = tfhc.newInstance();
for (Entry<String, Object> entry : params.entrySet()) {
Field f = tfhc.getDeclaredField(entry.getKey());
if (Modifier.isFinal(f.getModifiers())) {
continue;
}
boolean wasNotAcc = f.isAccessible();
if (wasNotAcc) {
f.setAccessible(true);
}
f.set(o, entry.getValue());
if (wasNotAcc) {
f.setAccessible(false);
}
}
return o;
} catch (InstantiationException | IllegalAccessException | SecurityException | NoSuchFieldException e) {
e.printStackTrace();
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment