Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Designing constructors around type erasure in Java

Yesterday, I was designing a Java class which I wanted to be initalized with Lists of various generic types:

TheClass(List<String> list) {
   ...
}

TheClass(List<OtherType> list) {
   ...
}

This will not compile, as the constructors have the same erasure.

I just went with factory methods differentiated by their names instead:

public static TheClass createWithStrings(List<String> list)
public static TheClass createWithOtherTypes(List<OtherType> list)

This is less than optimal, as there isn't a single obvious location where all the different options for creating instances are available.

I tried to search for better design ideas, but found surprisingly few results. What other patterns exist for designing around this problem?

like image 921
Internet Friend Avatar asked May 11 '26 18:05

Internet Friend


1 Answers

I would love to know a neat fix for this issue.

I encounter the same problem often, and I usually fix it by just introducing a dummy parameter (such as Void) to the constructor, which is of course not the most elegant fix, but the best one I know of so far.

like image 190
Gerard Avatar answered May 13 '26 06:05

Gerard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!