将对象属性映射到 Java 映射的最简单方法

Pab*_*lgo 1 java dictionary

有易于使用的工具将 java 类序列化为 JSON 字符串(gson),是否有任何主流库或 java 语言功能提供类似的功能将对象映射到 java Maps 中?

对于 C1 类来说,执行此操作的自然方法是:

class C1
{
  private int x;
  private int 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; }
}
Run Code Online (Sandbox Code Playgroud)

和对象o1:

C1 o1 = ...
Run Code Online (Sandbox Code Playgroud)

... 可能:

Map<String, Integer> result = new HashMap<>();
result.put("x",o1.getX());
result.put("y",o1.getY());
Run Code Online (Sandbox Code Playgroud)

gson 的工作方式非常简单(来自 gson 网站):

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用以下方法自己开发该工具:

Class.getDeclaredFields()
Run Code Online (Sandbox Code Playgroud)

但我想知道这个功能是否已经包含在任何主流库中。

Pab*_*lgo 5

最后,我决定实现我自己的映射器:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

一个愚蠢的使用示例:

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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

我的“映射器”方法需要输入对象来呈现按以下模式命名的 getter 和 setter:

(获取|设置)属性标题名称