Java 如何在实现泛型接口时返回具体类型

Java 如何在实现泛型接口时返回具体类型,java,generics,interface,Java,Generics,Interface,我有一个接口,它将由几个不同的类实现,每个类使用不同的类型和返回类型。返回类型可以从方法泛型类型推断出来,但是我在实现它时遇到了困难 当前界面如下所示: public interface TransformUtilsBase<T> { Class<?> transformToNhin(T request, BrokerContext brokerContext); } 公共接口转换库{ 类transformToNhin(T请求,BrokerContext,Br

我有一个接口,它将由几个不同的类实现,每个类使用不同的类型和返回类型。返回类型可以从方法泛型类型推断出来,但是我在实现它时遇到了困难

当前界面如下所示:

public interface TransformUtilsBase<T> {

    Class<?> transformToNhin(T request, BrokerContext brokerContext);
}
公共接口转换库{
类transformToNhin(T请求,BrokerContext,BrokerContext);
}
我希望Impl类看起来像:

public class TransformUtilsXCPD implements TransformUtilsBase<foo> {

    bar transformToNhin(foo request, BrokerContext brokerContext) {
        code here
    }
公共类TransformUtilsXCPD实现TransformUtilsBase{
bar transformToNhin(foo请求,BrokerContext BrokerContext){
代码在这里
}
在impl中,我知道返回类型应该是什么。在接口级别,没有办法知道

我可以一起放弃一个接口,只创建几个具有相同方法名的类,但我想将其形式化,因为它们都用于相同的目的。只是类型不同

或者我可以只使用一大类静态方法,因为它们是util操作,但是管理一个包含这么多同名方法和所有必需的helper方法(同样,所有方法都同名)的类变得非常困难

实现一个接口似乎是形式化功能的最佳选择,尽管我不能使用静态方法,我只是不知道如何处理返回类型

编辑:在界面上展开以显示完整示例,以防止进一步混淆。 接口

public interface TransformUtilsBase<T, U> {
    Class<?> transformToNhin(T request, BrokerContext brokerContext);
    Class<?> transformToXca(U request, BrokerContext brokerContext);
}
公共接口转换库{
类transformToNhin(T请求,BrokerContext,BrokerContext);
类transformToXca(U请求,BrokerContext BrokerContext);
}
恳求

公共类TransformUtilsXCPD实现TransformUtilsBase{
Baz transformToNhin(Foo请求,BrokerContext BrokerContext){code here}
Biz transformToXca(Bar请求,BrokerContext BrokerContext){code here}
}

为什么不同时声明返回类型的类型,比如

public interface TransformUtilsBase<T, S> {

    S transformToNhin(T request, BrokerContext brokerContext);
}
实现的类将声明为

public class TransformUtilsXCPD implements TransformUtilsBase<Foo, BarImpl> {

    BarImpl transformToNhin(Foo request, BrokerContext brokerContext) {
        //code here
    }
}
公共类TransformUtilsXCPD实现TransformUtilsBase{
BarImpl transformToNhin(Foo请求,BrokerContext BrokerContext){
//代码在这里
}
}

其中,
BarImpl
Bar
的一个子类。

吹毛求疵:
S扩展类
部分对于最后一个例子来说没有意义,因为
Bar
当然不能扩展
Class
。我只会使用
Class
之外的东西作为例子上限-我认为OP在他谢谢@PaulBellora我已经删除了
类作为上限,并给出了一些其他示例我应该道歉。我提交了一个界面/impl的缩短版本,试图更简洁,但我没有。我曾想过这个选项,但它看起来很笨拙,因为我将有4个泛型类型。我将创建一个编辑来显示是完整的版本。如果这仍然是最好的方法,我将使用它并将您的答案标记为正确。非常感谢您的洞察力。您是在尝试返回实际的Baz类,还是Baz的实例?您的编辑意味着它可能是第二个。好的一点。我正在尝试返回在转换期间创建的Baz类的特定实例通配符表示法是我所知道的最好的表达我想要的意图的方法,即只为方法变量提供泛型,返回类型可以通过它来确定。
public interface TransformUtilsBase<T, S extends Bar> {

    S transformToNhin(T request, BrokerContext brokerContext);
}
public class TransformUtilsXCPD implements TransformUtilsBase<Foo, BarImpl> {

    BarImpl transformToNhin(Foo request, BrokerContext brokerContext) {
        //code here
    }
}