反射机制为程序提供了分析类的能力。在程序运行期间,java运行时系统始终未所有的对象维护一个被称为运行时的类型标识。这个信息保存着每个对象所属的类足迹,保存在Class类的对象实例中,虚拟机根据运行时信息选择相应的方法执行。
java.lang.reflect包中提供了Field、Method和Constructor三个类分别描述类的域、方法和构造器。Class类中提供了不同的方法用来获取public或者全部声明的域、方法、构造器。
public class JsonMapper {
private static final Set> basics_num = new HashSet>();
private static final Set> basics_not_num = new HashSet>();
static {
basics_num.add(Integer.TYPE);
basics_num.add(Integer.class);
basics_num.add(Long.TYPE);
basics_num.add(Long.class);
basics_num.add(Byte.TYPE);
basics_num.add(Byte.class);
basics_num.add(Short.TYPE);
basics_num.add(Short.class);
basics_num.add(Float.TYPE);
basics_num.add(Float.class);
basics_num.add(Double.TYPE);
basics_num.add(Double.class);
basics_not_num.add(Boolean.TYPE);
basics_not_num.add(Boolean.class);
basics_not_num.add(Character.TYPE);
basics_not_num.add(Character.class);
}
public static String toJson(Object o) throws IllegalArgumentException, IllegalAccessException {
StringBuilder sb = new StringBuilder();
toJson(o, false, sb);
return sb.toString();
}
public static void toJson(Object o, boolean isField, StringBuilder sb)
throws IllegalArgumentException, IllegalAccessException {
if (o == null)
return;
Class clazz = o.getClass();
if (o instanceof CharSequence || basics_not_num.contains(clazz)) {
if (isField) {
sb.append("\"").append(String.valueOf(o)).append("\"");
} else {
sb.append("[\"").append(String.valueOf(o)).append("\"]");
}
}
else if (basics_num.contains(clazz)){
if (isField) {
sb.append(String.valueOf(o));
} else {
sb.append("[").append(String.valueOf(o)).append("]");
}
}
else if (isArray(o)) {
arrayToJson(o, sb);
} else if (isIterable(o)) {
iterableToJson(o, sb);
} else if (isMap(o)) {
mapToJson(o, sb);
}
else {
sb.append("{");
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
sb.append("\"");
sb.append(field.getName());
sb.append("\":");
Object fo = field.get(o);
toJson(fo, true, sb);
field.setAccessible(false);
if (i != (fields.length - 1))
sb.append(",");
}
sb.append("}");
}
}
private static boolean isArray(Object object) {
return object.getClass().isArray();
}
private static boolean isIterable(Object object) {
return object instanceof Iterable;
}
private static boolean isMap(Object object) {
return object instanceof Map;
}
private static void arrayToJson(Object o, StringBuilder sb)
throws IllegalArgumentException, IllegalAccessException {
sb.append("[");
// Object[] _object = (Object[]) object;
int len = Array.getLength(o);
for (int i = 0; i < len; i++) {
Object elem = Array.get(o, i);
toJson(elem, true, sb);
if (i != len - 1)
sb.append(",");
}
sb.append("]");
}
private static void iterableToJson(Object object, StringBuilder sb)
throws IllegalArgumentException, IllegalAccessException {
if (object == null)
return;
sb.append("[");
Iterable _object = (Iterable) object;
Iterator it = _object.iterator();
while (it.hasNext()) {
Object elem = it.next();
toJson(elem, true, sb);
if (it.hasNext())
sb.append(",");
}
sb.append("]");
}
private static void mapToJson(Object object, StringBuilder sb)
throws IllegalArgumentException, IllegalAccessException {
sb.append("{");
Map _object = (Map) object;
Set entrySet = _object.entrySet();
Iterator it = entrySet.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
sb.append("\"").append(key).append("\":");
toJson(value, true, sb);
if (it.hasNext())
sb.append(",");
}
sb.append("}");
}
static class ModelObject {
private int intField;
private Integer integerField;
private long longField;
private Long _longField;
private double doubleField;
private Double _doubleField;
private float floatField;
private Float _floatField;
private char charField;
private Character characterField;
private byte byteField;
private Byte _byteField;
private boolean booleanField;
private Boolean _booleanField;
private String stringField;
private String[] stringArrayField = {"s1", "s2", "s3"};
private int[] intArrayField = {1,2,3};
private Map mapField;
{
this.intField = 4;
this.integerField = new Integer(intField);
this.longField = 1000l;
this._longField = new Long(longField);
this.doubleField = 1.0;
this._doubleField = new Double(doubleField);
this.floatField = 2.0f;
this._floatField = new Float(floatField);
this.charField = 'c';
this.characterField = new Character(charField);
this.byteField = 0x01;
this._byteField = new Byte(byteField);
this.booleanField = true;
this._booleanField = new Boolean(booleanField);
this.stringField = "json";
this.mapField = new HashMap();
SubObject[] subs = { new SubObject("001"), new SubObject("002"), new SubObject("003") };
for (SubObject sub : subs)
this.mapField.put(sub.getNo(), sub);
}
}
static class SubObject {
private String no;
private List stringList;
public SubObject(String no) {
this.no = no;
List list = new ArrayList();
list.add("haha");
list.add("wowo");
list.add("hehe");
this.stringList = list;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public List getStringList() {
return stringList;
}
public void setStringList(List stringList) {
this.stringList = stringList;
}
}
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
ModelObject o = new ModelObject();
System.out.println(toJson(o));
System.out.println(toJson("abc"));
int[] a = {1,2,3,4};
System.out.println(toJson(a));
}
}