最后,我决定实现自己的映射器:
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class Serializer {
static public Map<String, Object> object2Map(Object o)
{
Class co = o.getClass();
Field [] cfields = co.getDeclaredFields();
Map<String, Object> ret = new HashMap<>();
for(Field f: cfields)
{
String attributeName = f.getName();
String getterMethodName = "get"
+ attributeName.substring(0, 1).toUpperCase()
+ attributeName.substring(1, attributeName.length());
Method m = null;
try {
m = co.getMethod(getterMethodName);
Object valObject = m.invoke(o);
ret.put(attributeName, valObject);
} catch (Exception e) {
continue;
}
}
return ret;
}
}
一个愚蠢的使用示例:
public class JavaUtilsTests {
static public class C1
{
public C1(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public void setX(int x) { this.x = x; }
public int getY() { return y; }
public void setY(int y) { this.y = y; }
private int x;
private int y;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
C1 o1 = new C1(1,2);
Map<String, Object> attributesMap = Serializer.object2Map(o1);
System.out.printf("x=%s\ty=%s\n", attributesMap.get("x"), attributesMap.get("y"));
}
}
我的“映射器”方法需要输入对象来呈现由以下模式命名的 getter 和 setter:
(get|set)attributeTitledName