Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从自定义对象获取参数映射_Java - Fatal编程技术网

Java 如何从自定义对象获取参数映射

Java 如何从自定义对象获取参数映射,java,Java,我有一些变量的类 我如何创建映射,其中key是变量的名称,value是这个变量的值 所以我想创造: 从自定义对象映射: 我创造了这样的东西: protected Map<String, String> getObjectParams(Object object) throws Exception { Map<String, String> result = new HashMap<>(); for (String field

我有一些变量的类

我如何创建映射,其中key是变量的名称,value是这个变量的值

所以我想创造:

从自定义对象映射

我创造了这样的东西:

protected Map<String, String> getObjectParams(Object object) throws Exception {
        Map<String, String> result = new HashMap<>();


        for (String field : (Iterable<String>) BeanUtils.describe(object).keySet()) {
            Object value = PropertyUtils.getProperty(object, field);
            if ((value != null) && (!"CLASS".equalsIgnoreCase(field)) {                     
                result.put(field, value.toString());
            }
        }

        return result;
}

然后map应该包含值MyCustomClass2A和MyCustomClass2B以及它们的值或类似的值

您必须在自定义类中重载toString()方法才能获得所需的值。比如:

public Class MyCustomClass1 {
  MyCustomClass2 customClass2;
  public String toString(){
      return customClass2.toString();
  }
}

public Class MyCustomClass2 {

  String a;
  String b;
  public String toString(){
          return a  + " " + b;
      }
}
这只是一个示例,根据需要更改toString()


或者使用此更新返回类型来映射或映射
并使用递归来填充子对象。

除了它的
toString
方法之外,你希望对象的“值”是什么?我希望toString值只是primite对象及其包装的等价物。当它不是基元对象时,应该有一些前缀。更新中的更多内容您是否尝试对对象进行完整描述,例如调试器可以执行的操作,例如:{“customClass2.a”:“a”,“customClass2.b”:“b”}?是的,类似于此,但我想将其保存在MaptoMap()中哪个类的函数?在我们的应用程序中,我们已经有了自定义的toString方法,我无法重写,而且这对我也没有帮助,因为在映射中将是键MyCustomClass2,而在值中将是该类中的2个值,这是错误的。请尝试此操作,抱歉,但我不理解此链接如何帮助我。它以完全不同的格式返回类的字符串
public Class MyCustomClass1 {
  MyCustomClass2 customClass2;
  public String toString(){
      return customClass2.toString();
  }
}

public Class MyCustomClass2 {

  String a;
  String b;
  public String toString(){
          return a  + " " + b;
      }
}