Created
December 7, 2014 08:11
-
-
Save jimbray/fac6120460326a1033f0 to your computer and use it in GitHub Desktop.
通过反射获取(修改)类的字段与值
This file contains 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 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