Java – how to return specific types when implementing a common interface
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 of generic type, but I encountered difficulties in performing this operation
The interface is as follows:
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 my opinion, I know what the return type should be There is no way to say it at the interface level
I can abandon an interface together and just use the same method name to complete several classes, but I want to formalize it because they are all used for the same purpose Only different types
Or I can have static methods of a large class because they are util operations, but it becomes cumbersome to use methods with the same name and all necessary help methods (all with the same name) to manage a class
Implementing the interface seems to be the best choice for formal functions, even if I can't execute static methods I don't know how to handle return types
Edit: expand on the interface to show a complete 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 } }
Solution
Why don't you declare a return type like this
public interface TransformUtilsBase<T,S> { S transformToNhin(T request,BrokerContext brokerContext); }
You can even "bind" your return type to a specific type (such as bar)
public interface TransformUtilsBase<T,S extends Bar> { S transformToNhin(T request,BrokerContext brokerContext); }
Implemented classes will be declared as
public class TransformUtilsXCPD implements TransformUtilsBase<Foo,BarImpl> { BarImpl transformToNhin(Foo request,BrokerContext brokerContext) { //code here } }
Barimpl is a subclass of bar