Let's say I have two constructors in my class:
public User (List<Source1> source){
...
}
public User (List<Source2> source) {
...
}
Let's say that both of these constructors provide the same information about a User and are equally valid ways to construct a user for different use cases.
In Java, you can't do this because of type erasure -- Java won't accept two constructors that have as parameters List< ? >.
So, what is the way to get around this? What is a solution that is not overkill but still respects basic OO? It seems wrong to have to construct a factory method or other interface around this just because Java doesn't have strong generics support.
Here are the possibilities I can think of:
1) Accept a List<?>
as a parameter for the constructor and parse in the constructor which kind of logic you need, or throw an exception if it's not any of the accepted types.
2) Create a class that accepts either List, constructs the appropriate User object, and returns it.
3) Create wrappers around List<Source1>
and List<Source2>
that can be passed to the User constructor instead.
4) Subclass this guy with two classes, where all of the functionality is inherited except for the constructor. The constructor of one accepts Source1, the other accepts Source2.
5) Wrap this guy with a builder where are two different builder methods for the two different sources of data for instantiation.
My questions are these:
1) Is the need to do this a flaw with Java, or an intentional design decision? What is the intuition?
2) Which solution is strongest in terms of maintaining good code without introducing unneeded complexity? Why?
This question is similar: Designing constructors around type erasure in Java but does not go into specifics, it just suggests various work-arounds.