「Java入門」getClass().getDeclaredFields()の使い方

2017年9月23日

Javaコード:
public static String getToString(Object obj) {
String result = “";
Field[] fields = obj.getClass().getDeclaredFields();
StringBuffer strBuf = new StringBuffer();
strBuf.append(obj.getClass().getName());
strBuf.append(“(“);
for (int i = 0; i < fields.length; i++) {
Field fd = fields[i];
try {
Method method = obj.getClass().getMethod(“get" + toUpperCaseFirstOne(fd.getName()));
if(method.invoke(obj) != null) {
strBuf.append(fd.getName() + “:");
strBuf.append(method.invoke(obj) + “,");
}
} catch (NoSuchMethodException e) {
//TODO
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}

}

Java

Posted by arkgame