本文介绍了泛型:无法从< capture#1-of转换?扩展对象,D>到< S,D>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下类结构:

public interface CopyMapper<S, D> {
    public D map(S sourceObject);
}

public interface CopyMapperFactory {
    public <S, D> CopyMapper<S, D> getMapper(Class<S> sourceClass, Class<D> destinationClass);
}

public class Mapper {
    public <S, D> D map(S source, Class<D> destinationClass) {
        //This is where I get compile time error
        CopyMapper<S, D> copyMapper = mapperFactory.getMapper(source.getClass(), destinationClass);
        return copyMapper.map(source);
    }

我的Eclipse编译器给我以下错误:

My Eclipse compilator gives me the following error:

Type mismatch: cannot convert from CopyMapper<capture#1-of ? extends Object,D> to CopyMapper<S,D>

据我所知,所有通用类型都扩展了Object,所以我看不出问题出在哪里?

As far as I know, all generic types extend Object, so I don't see where the problem is?

我们正在尝试保留一个接口.这是界面的原始方法:

We are trying to preserve an interface. This is the original method of the interface:

<T> T map(Object source, Class<T> destinationClass)

我对其进行了一些微调,以使使用该接口的类不会受到影响:

I tweaked it a little bit so that the classes that use the interface don't get affected:

<S, D> D map(S source, Class<D> destinationClass);

基本上,我们正在映射Pojo,我们一直在使用DozerMapper,但是现在,主要的架构师希望编译时安全,而DozerMapper却没有.例如,如果一个pojo的字段被更新(重命名,删除),我们需要手动更新xml,该xml描述了pojo的映射(例如,在非平凡映射的情况下使用xml,例如,当pojo的字段名称并不完全对应,通常是这样)

Basically, we are mapping Pojo's, we've been using DozerMapper, but now, the major architect wants compile time safety, and the DozerMapper isn't. For example if a pojo's field gets updated (renamed, deleted) we need to manually update the xml, that describes the mapping between the pojo's (the xml is used in case of nontrivial mapping, for example, when the names of fields of the pojo's don't correspond completely, which is often the case)

现在,我们有复制类,其中有数百个,每个类用于pojo之间的映射.我们正在尝试使用Factory Design模式根据源类和目标类返回特定的映射器类(实现CopyMapper接口).

Now, we have copy classes, hundreds of them, one for each mapping between pojo's. We are trying to use the Factory Design patter to return a specific mapper class (implementing the CopyMapper interface) based on the source class and destination class.

推荐答案

getClass方法返回Class<?>而不是Class<S>,正如我认为的那样.请参见中的 Object#getClass API.

The getClass method returns Class<?> and not Class<S>, as I think you are expecting. See Object#getClass in the API.

当它返回Class<?>时,您会丢失类型信息,因此您确实拥有以下信息:

As it returns Class<?> you lose type information, so you really have this:

CopyMapper<?, D> copyMapper = mapperFactory.getMapper(source.getClass(), destinationClass);

您知道源类是S,所以我认为您可以放心地添加演员表,但会收到警告:

You know source class is S so I think you can safely add a cast, but you will get a warning:

CopyMapper<S, D> copyMapper = mapperFactory.getMapper((Class<S>)source.getClass(), destinationClass);

这篇关于泛型:无法从&lt; capture#1-of转换?扩展对象,D&gt;到&lt; S,D&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:34