【问题标题】:Raw use of parameterized class Java (implementing interface with generic param type) [duplicate]参数化类Java的原始使用(使用通用参数类型实现接口)[重复]
【发布时间】:2021-03-03 10:36:25
【问题描述】:

我收到警告“原始使用参数化类 'MapperService' 和“未经检查地调用 'mapSourceToBehandlerKrav(T)' 作为原始类型的成员......来自 IntelliJ。我并没有真正掌握泛型的概念,试图弄清楚。但是对这些警告的一些解释和解决方案可能会有所帮助

界面:

public interface MapperService<T> {
    Behandlerkrav mapSourceToBehandlerkrav(T sourceInput) throws DataSourceException, MapperException;
}

实现类:

public class XMLToDomainMapper implements MapperService {

    public Behandlerkrav mapSourceToBehandlerkrav(Object input) throws DataSourceException, MapperException {

        if (!(input instanceof File)) {
            throw new DataSourceException(
                "Input er av ugyldig type: " + input.getClass() + " | tillat type = " + "File");
        }

        // More stuff
    }

调用实现类(出现警告的地方):

public class InnrapporteringServiceImpl implements InnrapporteringService {
    MapperService kildesystemInputMapper; <-- IntelliJ WARNING HERE

    public InnrapporteringServiceImpl(XMLToDomainMapper mapper) {
        this.kildesystemInputMapper = mapper;
    }

    @ServiceActivator(inputChannel = "sftChannel")
    public void init(Message<File> message) {
        // call mapper service
        // call persistence service
        // call reporting service
        var timestamp = message.getHeaders().getTimestamp();

        Behandlerkrav behandlerkrav = kildesystemInputMapper.mapSourceToBehandlerkrav(message.getPayload()); <-- IntelliJ WARNING here
    }
}

【问题讨论】:

  • 您是否应该将 kildesystemInputMapper 字段类型声明为 MapperService[XMLToDomainMapper] 或提及您的映射器是否扩展了任何父映射器类。

标签: java spring generics interface


【解决方案1】:

MapperService 接口旨在使用类型进行参数化。

这允许它检查mapSourceToBehandlerkrav 的参数是否属于它所期望的类型。

如果你把 XMLToDomainMapper 写成:

class XMLToDomainMapper implements MapperService<File> {
 ...
}

然后你会在编译时检查传递的参数是File,你就不需要了:

if (!(input instanceof File)) {
            throw new DataSourceException(
                    "Input er av ugyldig type: " + input.getClass() + " | tillat type = " + "File");
        }

正如您在当前实现中所做的那样 - 不可能使用不是 File 的任何类型的参数来调用它。

【讨论】:

  • 太漂亮了,谢谢。能接受就接受
猜你喜欢
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
相关资源
最近更新 更多