【问题标题】:Converting several java variables to a single object using object serialization使用对象序列化将多个 java 变量转换为单个对象
【发布时间】:2017-10-06 04:37:26
【问题描述】:

以下代码用于从 java 方法中获取多个参数。

import java.io.Serializable;

public class Example implements Serializable{
 void getValues(String m,int x, int y){
}
}

如何使用对象序列化将 3 个参数 m、x 和 y 放入单个对象中?

【问题讨论】:

  • 我没有理解你的问题。这是你想要的吗? class Bla { private String m; private int x, private int y; // constructor(s), setters and getters... } 然后void getValues(Bla bla)...
  • 将 m、x 和 y 包装到单个对象变量中

标签: java object parameters serializable


【解决方案1】:

您可以使用Map

创建一个包含 3 个参数的新类

public class ThreeParameters implements Serializable {
    private final String m;
    private final int x;
    private final int y;

    ...
    // Remember to override equals and hashcode
}

使用ThreeParameters 作为键创建Map

public Map<ThreeParameters, Object> map = new HashMap<>();

.... // Add elements with put 

// map is a Serializable object as required 

【讨论】:

  • thanx 如果我想将对象反序列化为 3 个初始变量,那么我该怎么做呢?
  • 将 getter 添加到 ThreeParameters 类并根据需要获取它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-12
  • 2013-04-15
  • 2014-05-18
相关资源
最近更新 更多