Skip to content
Advertisement

Instantiate generic classes with different constructor arguments

I have two similar classes, Foo and Bar

JavaScript

And I’ve got two methods in another class that creates a Set of Foo (1st method) and Bar (2nd method) and are pretty much the same. The first one:

JavaScript

And the second one:

JavaScript

As you can see, both methods are pretty much the same so I thought I could use generics to use only one method. My approach would be something like this:

JavaScript

I’ve tested this and it’s supposed to be working but my question is, what would happen if Foo or Bar would have a different constructor (so for instance, Bar would have another String as the 2nd parameter). All I can think about is to check the instance of the class and pick one of the two constructors (something like this)

JavaScript

Is there a better way of achieving this? Is this even a good practice? Any tip is always appreciated. Thanks in advance!

Advertisement

Answer

It seems to me that it would be better to take a Function<String, T> instead of a Class<T>. That way you don’t need reflection, and callers can pass in constructors, factory methods, lambdas that use multi-parameter constructors, whatever they want. So your method would be:

JavaScript

I suspect this could be written more simply using streaming, but that’s a separate issue. (I did take the opportunity to use an enhanced-for loop for simplicity though.)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement