「Java入門」reflectionでObjectのfieldを再帰的に出力する

Javaコード:
package com.cft;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.lang.reflect.ParameterizedType;

public class ReflectField {

public Integer id;
public String name;
public List<String> names;
public List<InnerClass> filter;

public static class InnerClass {
public Integer a;
public String b;
}

@SuppressWarnings(“unchecked")
public static <T> void output(Object obj, Class<T> c) {
try {
for (Field field : c.getFields()) {
System.out.println(String.format(
“field name is %s",
field.getName()));
if (getInteger(obj, field) != null)
continue;
if (getString(obj, field) != null)
continue;
if (field.getType() == List.class) {
System.out.println(String.format(
“%s is List, actual class = %s",
field.getName(),((ParameterizedType) field.getGenericType())
.getActualTypeArguments()[0]));
@SuppressWarnings(“rawtypes")
Class actualClass =
((Class) ((ParameterizedType) field.getGenericType())
.getActualTypeArguments()[0]);
if (actualClass == String.class) {
List<String> lists = (List<String>) field.get(obj);
for (String s : lists) {
System.out.println(String.format(“value = %s", s));
}
} else {
List<Object> lists = (List<Object>) field.get(obj);
for (Object o : lists) {
output(o, actualClass);
}
}
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
public static <T> Integer getInteger(Object obj, Field field)
throws Exception {
if (field.getType() == Integer.class) {
System.out.println(String.format(
“%s is Integer, value = %d",
field.getName(),
field.get(obj)));
return (Integer) field.get(obj);
} else {
return null;
}
}
public static <T> String getString(Object obj, Field field)
throws Exception {
if (field.getType() == String.class) {
System.out.println(String.format(
“%s is String, value = %s",
field.getName(),
field.get(obj)));
return (String) field.get(obj);
} else {
return null;
}
}
public ReflectField() {
names = new ArrayList<String>();
filter = new ArrayList<InnerClass>();
}

public static void main(String[] args) {
ReflectField ss = new ReflectField();
ss.id = 1;
ss.name = “reflect field is samples.";
ss.names.add(“reflect field is samples.");
InnerClass f = new InnerClass();
f.a = 24;
ss.filter.add(f);
ReflectField.output(ss, ss.getClass());

}

}
実行結果:
field name is id
id is Integer, value = 1
field name is name
name is String, value = reflect field is samples.
field name is names
names is List, actual class = class java.lang.String
value = reflect field is samples.
field name is filter
filter is List, actual class = class cft.ReflectField$InnerClass
field name is a
a is Integer, value = 24
field name is b
b is String, value = null

Java

Posted by arkgame