So I'm building a test library that I will mainly use for personal use however I have a question.
With Java, if you have 2 or more constructors in your class, if you wish to call one from another, it must be the first thing you do. This is problematic for me as I have the below setup.
public Constructor(TypeA a, TypeB b, TypeC c) {
if (c.getData() == null) throw new IllegalArgumentException("");
this(a, b, c.getOtherData());
}
public Constructor(TypeA a, TypeB b, TypeD d) {
// stuff happens
}
How can I do this, avoiding the, "Constructor call must be the first statement in a constructor" error?
You cannot do what you want with constructors. Instead use a static factory method like this:
public static TypeThing buildMyThing(TypeA a, TypeB b, TypeC c) {
if (c.getData() == null) throw new IllegalArgumentException("");
return new TypeThing(a, b, c.getOtherData());
}
public Constructor(TypeA a, TypeB b, TypeD d) {
// stuff happens
}
One option (probably bad):
Check for getData == null and throw the exception as first thing in
c.getOtherData()`. That would be the first method being executed.
Other Option: Have a method like,
helper() {
if (getData() == null) throw new Exception();
return getOtherData();
}
and from you constructor, call c.helper()
instead of c.getOtherData()
How about creating a static factory method?
public static Constructor newInstance(TypeA a, TypeB b, TypeC c) {
if (c.getData() == null) throw new IllegalArgumentException("");
return new Constructor(a, b, c);
}
private Constructor(TypeA a, TypeB b, TypeC c) {
this(a, b, c.getOtherData());
}
private Constructor(TypeA a, TypeB b, TypeD d) {
// stuff happens
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With