I have an interface that will be implemented by several different classes, each using different types and return types. The return type can be inferred from the method generic type, but I'm having trouble implementing this.
The interface looks like this currently:
public interface TransformUtilsBase<T> {
Class<?> transformToNhin(T request, BrokerContext brokerContext);
}
I want the Impl class to look like:
public class TransformUtilsXCPD implements TransformUtilsBase<foo> {
bar transformToNhin(foo request, BrokerContext brokerContext) {
code here
}
In the impl I know what the return type should be. At the interface level there is no way to tell.
I could just forego an interface all together, and just make several classes all with the same method names, but I wanted to formalize it, since they are all getting used for the same purpose. Only the types are different.
Or I could just have one big class of static methods since they are util operations, but it was becoming unwieldy to manage a class with so many methods with the same name, and all the necessary helper methods (again all with the same name).
Implementing an interface seems like the best option to formalize functionality, even though I'm not able to do static methods. I just can't figure out how to deal with the return types.
edit: expanding on interface to show the full example to prevent further confusion. Interface
public interface TransformUtilsBase<T, U> {
Class<?> transformToNhin(T request, BrokerContext brokerContext);
Class<?> transformToXca(U request, BrokerContext brokerContext);
}
Impl
public class TransformUtilsXCPD implements TransformUtilsBase<Foo, Bar> {
Baz transformToNhin(Foo request, BrokerContext brokerContext) { code here }
Biz transformToXca(Bar request, BrokerContext brokerContext) { code here }
}
why don't you declare the type for the return type as well, something like this
public interface TransformUtilsBase<T, S> {
S transformToNhin(T request, BrokerContext brokerContext);
}
you can even "bind" your return type to be of specific type (say Bar
)
public interface TransformUtilsBase<T, S extends Bar> {
S transformToNhin(T request, BrokerContext brokerContext);
}
and the classes who implement will declare as
public class TransformUtilsXCPD implements TransformUtilsBase<Foo, BarImpl> {
BarImpl transformToNhin(Foo request, BrokerContext brokerContext) {
//code here
}
}
where BarImpl
is an subclass of Bar
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