具有List的Java泛型接口< T>不接受对象类型

olhwl3o2  于 2023-01-29  发布在  Java
关注(0)|答案(4)|浏览(160)

我正在尝试实现一个系统如下:
DtoMapper:这是一个接口,它定义了任何第三方Map器都应该返回对象的契约

public interface DtoMapper<T> {

    /**
     * Converts list of T into FooResponse
     * @param List of T
     * @return FooResponse
     */
    FooResponse convertToFooResponse(final List<T> rewards);

FooMapper:实现DtoMapper,传递Bar的List作为方法参数,但是编译器不喜欢我对方法实现的重写,需要第二个实现(底部)。

public final class FooMapper implements DtoMapper {

    @Override
    FooResponse convertToFooResponse(final List<Bar> listOfBars) {
        ... Logic
    }

     @Override
    public convertToFooResponse(final List listOfBars) {
        ... I dont want this
    }

我怎样才能使我的接口满足这个需求,以便在将来实现public convertToFooResponse(final list<Snafu> listOfSnafus);

zqdjd7g9

zqdjd7g91#

您需要显式实现DtoMapper<Bar>,而不是DtoMapper
示例:

public interface DtoMapper<T> {

    /**
    * Converts list of T into FooResponse
    * @param List of T
    * @return FooResponse
    */
    FooResponse convertToFooResponse(final List<T> rewards);
}

public class FooMapperImplementation implements DtoMapper<Bar> {
    @Override
    public FooResponse convertToFooResponse(List<Bar> rewards) {
        return null;
    }
}
pcrecxhr

pcrecxhr2#

实现类时需要传递泛型规范:

public final class FooMapper implements DtoMapper<Bar> {
// Here -----------------------------------------^

    @Override
    FooResponse convertToFooResponse(final List<Bar> listOfBars) {
        ... Logic
    }
cu6pst1q

cu6pst1q3#

您忘记了参数化类型

class FooResponse{}
class First{}
class Second{}

public interface DtoMapper<T> {
    FooResponse convertToFooResponse(final List<T> rewards);    
}

class FirstMapper implements DtoMapper<First> {
    @Override
    public FooResponse convertToFooResponse(List<First> list) {
        return null;
    }
}

class SecondMapper implements DtoMapper<Second> {
    @Override
    public FooResponse convertToFooResponse(List<Second> list) {
        return null;
    }
}
ffvjumwh

ffvjumwh4#

在调用方法之前,可以创建一个具有接口类型的新列表。

List<InterfaceType> listWithInterfaceType = new ArrayList<>(listWithObjectType);

相关问题