Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimbray/fac6120460326a1033f0 to your computer and use it in GitHub Desktop.
Save jimbray/fac6120460326a1033f0 to your computer and use it in GitHub Desktop.
通过反射获取(修改)类的字段与值
public static Object reflect2(Object obj) {
if (obj == null)
return null;
Field[] fields = obj.getClass().getDeclaredFields();
for (int j = 0; j < fields.length; j++) {
fields[j].setAccessible(true);
// 字段名
System.out.print(fields[j].getName() + ",");
// 字段值
if (fields[j].getType().getName().equals(
java.lang.String.class.getName())) {
// String type
try {
// System.out.print(fields[j].get(obj));
// fields[j].set(obj, fields[j].get(obj));
String value = (String)(fields[j].get(obj));
//if(!TextUtils.isEmpty(value)) {
//String[] change_result = ClerkUtils.switchToStandardJSON((String)(fields[j].get(obj)));
//fields[j].set(obj, change_result[0]);
//}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (fields[j].getType().getName().equals(
java.lang.Integer.class.getName())
|| fields[j].getType().getName().equals("int")) {
// Integer type
try {
System.out.println(fields[j].getInt(obj));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 其他类型。。。
}
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment