参数化 class Java 的原始使用(使用通用参数类型实现接口)

Raw use of parameterized class Java (implementing interface with generic param type)

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

接口:

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

实施class:

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
    }

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

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
    }
}

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