[英]Generics: cannot convert from <capture#1-of ? extends Object,D> to <S,D>
I have the following class structure: 我具有以下类结构:
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);
}
My Eclipse compilator gives me the following error: 我的Eclipse编译器给我以下错误:
Type mismatch: cannot convert from CopyMapper<capture#1-of ? extends Object,D> to CopyMapper<S,D>
As far as I know, all generic types extend Object
, so I don't see where the problem is? 据我所知,所有泛型类型都扩展了
Object
,所以我不知道问题出在哪里?
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);
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. 基本上,我们正在映射Pojo,我们一直在使用DozerMapper,但是现在,主要的架构师希望编译时安全,而DozerMapper则不需要。 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的字段被更新(重命名,删除),我们需要手动更新xml,它描述了pojo的映射(例如,在非平凡映射的情况下使用xml,例如,当pojo的字段名称并不完全对应(通常是这种情况)
Now, we have copy classes, hundreds of them, one for each mapping between pojo's. 现在,我们有了复制类,其中有数百个,分别对应于pojo之间的每个映射。 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. 我们正在尝试使用Factory Design模式来基于源类和目标类返回特定的映射器类(实现
CopyMapper
接口)。
The getClass
method returns Class<?>
and not Class<S>
, as I think you are expecting. 正如我认为的那样,
getClass
方法返回Class<?>
而不是Class<S>
。 See Object#getClass
in the API. 请参阅API中的
Object#getClass
。
As it returns Class<?>
you lose type information, so you really have this: 当它返回
Class<?>
您会丢失类型信息,因此您确实拥有以下信息:
CopyMapper<?, D> copyMapper = mapperFactory.getMapper(source.getClass(), destinationClass);
You know source class is S
so I think you can safely add a cast, but you will get a warning: 您知道源类是
S
所以我认为您可以放心地添加强制类型转换,但是会收到警告:
CopyMapper<S, D> copyMapper = mapperFactory.getMapper((Class<S>)source.getClass(), destinationClass);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.