[英]Java: Overloading constructors which call each other
Consider a class which is instanciated from a data found in a CSV line, and stores some of its fields. 考虑一个从CSV行中找到的数据实例化的类,并存储它的一些字段。 It makes sense to create two constructors for this class -one from the raw CSV line, and one with explicit variable assignment. 为此类创建两个构造函数是有意义的 - 一个来自原始CSV行,另一个具有显式变量赋值。
eg, 例如,
public MyClass(String csvLine)
{
String[] fields = StringUtils.split(csvLine, ',');
this(fields[3], fields[15], Integer.parseInt([fields[8]));
}
public MyClass(String name, String address, Integer age)
{
this.name=name;
this.address=address;
this.age=age;
}
In Java, this fails because: 在Java中,这会失败,因为:
Constructor call must be the first statement in a constructor WhereOnEarth.java 构造函数调用必须是构造函数WhereOnEarth.java中的第一个语句
What's the proper way to implement this? 实现这个的正确方法是什么?
Here is my take: 这是我的看法:
public class MyClass {
public static MyClass fromCsvLine(String csvLine) {
String[] fields = StringUtils.split(csvLine, ',');
return new MyClass(fields[3], fields[15], Integer.parseInt([fields[8]));
}
//...
}
Usage: 用法:
MyClass my = MyClass.fromCsvLine("...");
Create a method 创建一个方法
private init(String name, String address, Integer age) {}
Call it from both constructors. 从两个构造函数中调用它。
I would not mix the class that represents the parsed content and the content parsing class. 我不会混合代表解析内容的类和内容解析类。 I would create a MayClassFactory or something along those lines: 我会创建一个MayClassFactory或类似的东西:
public class MyClassFactory {
public MyClass fromCsvLine(String csvLine) {
String[] fields = StringUtils.split(csvLine, ',');
return new MyClass(fields[3], fields[15], Integer.parseInt([fields[8]));
}
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.