【问题标题】:Best way to add a string based constructor to a Java class?将基于字符串的构造函数添加到 Java 类的最佳方法?
【发布时间】:2010-03-04 03:39:55
【问题描述】:

假设我有一些课,例如福:

public class Foo {
    private Integer x;
    private Integer y;

    public Foo(Integer x, Integer y) {
        this.x = x;
        this.y = y;
    }


    public String toString() {
        return x + " " + y;
    }
}

现在,我想添加一个构造函数,它的参数是一个代表 Foo 的字符串,例如Foo("1 2") 将构造一个 x=1 和 y=2 的 Foo。由于我不想复制原始构造函数中的逻辑,因此我希望能够执行以下操作:

public Foo(string stringRepresentation) {
    Integer x;
    Integer y;

    // ...
    // Process the string here to get the values of x and y.
    // ...

    this(x, y);
}

但是,Java 不允许在调用 this(x, y) 之前使用语句。有一些公认的解决方法吗?

【问题讨论】:

  • 为什么一定要叫这个(x, y)?为什么不直接设置 x 和 y?
  • 正如我在原始问题中提到的,我希望避免在现有构造函数中重复逻辑。例如,我想稍后添加某种验证,然后我只需要修改原始构造函数而不是两者。

标签: java constructor tostring


【解决方案1】:

由于这两个值,这种特殊情况有点尴尬,但您可以做的是调用静态方法。

  public Foo(Integer x, Integer y) {
      this(new Integer[]{x, y});
  }

  public Foo(String xy) {
      this(convertStringToIntegers(xy));
  }

  private Foo(Integer[] xy) {
      this.x = xy[0];
      this.y = xy[1];
  }

  private static Integer[] convertStringToIntegers(String xy) {
      Integer[] result;
      //Do what you have to do...
      return result;
  }

话虽如此,如果这个类不需要被子类化,那么让构造函数全部私有并拥有一个公共静态工厂方法会更清晰、更好、更符合规范:

  public static Foo createFoo(String xy) {
       Integer x;
       Integer y;
        //etc.
        return new Foo(x, y);
  }

【讨论】:

  • 第二个选项正是我想要的。谢谢!
【解决方案2】:

另一种选择是,您可以考虑拥有一个静态工厂方法,该方法接受一个字符串参数并返回一个 Foo 实例。这类似于 Integer 类中 valueOf(String s) 方法使用的方法。

【讨论】:

  • +1 工厂方法绝对是解决构造函数的许多不灵活问题的好方法。
【解决方案3】:

创建一个方法来处理两个构造函数中所需的初始化并调用它而不是 this(...)。

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 2014-10-15
    • 2012-01-13
    • 2020-10-04
    相关资源
    最近更新 更多