List <t>的Java通用接口不接受对象类型

时间:2016-09-08 11:02:54

标签: java generics interface compiler-errors

我正在尝试按如下方式实施一个系统:

DtoMapper:这是一个定义合约的接口,任何第三方映射器都应该返回对象

    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列表作为方法参数,但是编译器不喜欢我对方法实现的重写,并且想要第二个实现(底部)。

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);

3 个答案:

答案 0 :(得分:3)

您需要明确地实施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;
    }
}

答案 1 :(得分:3)

实现类时需要传递通用规范:

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

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

答案 2 :(得分:1)

您忘记了参数化类型

public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {
        this.ToTable("User");
        this.HasKey<int>(p => p.Id);
        this.Property(u => u.UserPin).IsRequired().HasMaxLength(2000);
    }
}