I know that if I have an overloaded method in Java that can accept a parameter of several different types, and I want to pass null
to the method, I need to explicitly cast it to one of the accepted types. My question is, is it possible to choose which version of the method is called on null
from within the method itself (e.g. by adding another overload to handle the null
)?
My problem is the following - I have a class with an overloaded constructor that accepts one parameter:
public class MyClass {
public MyClass(A arg) {
// do something
}
public MyClass(B arg) {
// do something else
}
}
The use case is such that if the class is constructed with a null
, then only the second version of the constructor makes sense. But having to do new MyClass((B)null)
every time is error-prone. If I accidentally use the cast to A
, then the wrong constructor gets executed. And I also cannot introduce the following check in my A
constructor:
if (arg == null) {
this((B)arg);
}
because this(...)
is not the first statement. Of course, I can duplicate the code from the B
constructor inside this check, or introduce another method to do what the B
constructor does and then call it from both inside the constructor and inside this check, but this doesn't seem like a "clean" solution (and may not always be possible, e.g. in the case of cascading constructors).
Is there a way for me to only have to do new MyClass(null)
and have the B
version of the constructor executed every time?
I tried to add this overload, but the compiler complained:
public MyClass(null arg) {
this((B)arg);
}