参数化类java的原始用法(用泛型param类型实现接口)

iqxoj9l9  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(433)

这个问题在这里已经有答案了

什么是原始类型?为什么不使用它(15个答案)
上个月关门了。
我得到警告“原始使用参数化类'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
    }

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

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

jjjwad0x1#

这个 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 .

相关问题