public abstract class Refl {
/** Use: Refl.<TargetClass>get(myObject,"x.y[0].z"); */
public static<T> T get(Object obj, String fieldPath) {
return (T) getValue(obj, fieldPath);
}
public static Object getValue(Object obj, String fieldPath) {
String[] fieldNames = fieldPath.split("[\\.\\[\\]]");
String success = "";
Object res = obj;
for (String fieldName : fieldNames) {
if (fieldName.isEmpty()) continue;
int index = toIndex(fieldName);
if (index >= 0) {
try {
res = ((Object[])res)[index];
} catch (ClassCastException cce) {
throw new RuntimeException("cannot cast "+res.getClass()+" object "+res+" to array, path:"+success, cce);
} catch (IndexOutOfBoundsException iobe) {
throw new RuntimeException("bad index "+index+", array size "+((Object[])res).length +" object "+res +", path:"+success, iobe);
}
} else {
Field field = getField(res.getClass(), fieldName);
field.setAccessible(true);
try {
res = field.get(res);
} catch (Exception ee) {
throw new RuntimeException("cannot get value of ["+fieldName+"] from "+res.getClass()+" object "+res +", path:"+success, ee);
}
}
success += fieldName + ".";
}
return res;
}
public static Field getField(Class<?> clazz, String fieldName) {
Class<?> tmpClass = clazz;
do {
try {
Field f = tmpClass.getDeclaredField(fieldName);
return f;
} catch (NoSuchFieldException e) {
tmpClass = tmpClass.getSuperclass();
}
} while (tmpClass != null);
throw new RuntimeException("Field '" + fieldName + "' not found in class " + clazz);
}
private static int toIndex(String s) {
int res = -1;
if (s != null && s.length() > 0 && Character.isDigit(s.charAt(0))) {
try {
res = Integer.parseInt(s);
if (res < 0) {
res = -1;
}
} catch (Throwable t) {
res = -1;
}
}
return res;
}
}
It supports fetching fields and array items, e.g.:
System.out.println(""+Refl.getValue(b,"x.q[0].z.y"));
there is no difference between dots and braces, they are just delimiters, and empty field names are ignored:
System.out.println(""+Refl.getValue(b,"x.q[0].z.y[value]"));
System.out.println(""+Refl.getValue(b,"x.q.1.y.z.value"));
System.out.println(""+Refl.getValue(b,"x[q.1]y]z[value"));