我有以下课程:
public interface IEntity<T extends IEntity<T>>
{
T createNewEntity(IEntityCreator creator);
}
public interface IEntityCreator
{
<T extends IEntity<T>> T createNewEntity(T source);
}
public abstract class EntityBase<T extends EntityBase<T>> implements IEntity<T>
{
@Override
public T createNewEntity(IEntityCreator creator)
{
return creator.createNewEntity(this); //Error here
}
}
我收到以下错误:
“绑定不匹配:IEntityCreator类型的泛型方法createNewEntity(T)不适用于参数(EntityBase)。推断类型EntityBase不是有界参数的有效替代品&gt;”
我尝试使用以下代码采用不同的方法但没有成功:
public interface IEntity<T extends IEntity<T>>
{
T createNewEntity(IEntityCreator<T> creator);
}
public interface IEntityCreator<T extends IEntity<T>>
{
T createNewEntity(T source);
}
public abstract class EntityBase<T extends EntityBase<T>> implements IEntity<T>
{
@Override
public T createNewEntity(IEntityCreator<T> creator)
{
return creator.createNewEntity(this); //Error here
}
}
这次编译器说:
“IEntityCreator类型中的方法createNewEntity(T)不适用于参数(EntityBase)”
此错误的原因是什么?我该如何纠正?
由于
答案 0 :(得分:0)
这里有漂亮的外接模式,但这会编译......
public interface IEntity<T extends EntityBase<T>>
{
T createNewEntity(IEntityCreator<T> creator);
}
public interface IEntityCreator<T extends EntityBase<T>>
{
T createNewEntity(EntityBase<T> entityBase);
}
public abstract class EntityBase<T extends EntityBase<T>> implements IEntity<T>
{
@Override
public T createNewEntity(IEntityCreator<T> creator)
{
return creator.createNewEntity(this);
}
}
答案 1 :(得分:0)
错误的原因是IEntityCreator.createNewEntity()
需要T
来实现IEntity<T>
,而您正在传递EntityBase<T>
,因此它应该实现IEntity<EntityBase<T>>
,它没有。
你需要明确地将this
强制转换为T
(来自EntityBase<T>
的实际实现IEntity<T>
的派生类),就像Wundwin Born在评论中所建议的那样:
public T createNewEntity(IEntityCreator creator) {
return creator.createNewEntity((T)this);
}