Java: overload constructors that call each other

Consider a class that comes from the data found in a CSV string and stores some of its fields. It makes sense to create two constructors for this class - one from the original CSV line and one with an explicit variable assignment.

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 is not possible because:

The constructor call should be the first statement in the constructor WhereOnEarth.java

What is the right way to implement this?

+4
source share
3 answers

I would not mix the class representing the analyzed content and the content analysis class. I would create a MayClassFactory or something like that:

 public class MyClassFactory { public MyClass fromCsvLine(String csvLine) { String[] fields = StringUtils.split(csvLine, ','); return new MyClass(fields[3], fields[15], Integer.parseInt([fields[8])); } //... } 
+5
source

Here is my trick:

 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])); } //... } 

Using:

 MyClass my = MyClass.fromCsvLine("..."); 
+7
source

Create method

 private init(String name, String address, Integer age) {} 

Call him from both designers.

+5
source

Source: https://habr.com/ru/post/1399772/


All Articles