2014-09-26 81 views
0

我有以下類別:獲得「不適用」與泛型類型編譯錯誤

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不是有效的替代參數>「

我嘗試了以下代碼的不同方法,但沒有成功:

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

你的第一行:公共接口IEntity > 。在IEntity 2014-09-26 09:06:29

+0

嘗試在'EntityBase.createNewEntity'聲明中替換'EntityBase ' – talex 2014-09-26 09:13:47

+1

如何用'return creator.createNewEntity((T)this'')替換? – 2014-09-26 09:14:37

回答

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); 
    } 
} 
0

錯誤的原因是IEntityCreator.createNewEntity()需要T它實現IEntity<T>,你是路過EntityBase<T>,所以應該實施IEntity<EntityBase<T>>,它不這樣做。

您需要顯式轉換thisT(從EntityBase<T>這實際上實現IEntity<T>派生類),如Wundwin出生建議在註釋:

public T createNewEntity(IEntityCreator creator) { 
    return creator.createNewEntity((T)this); 
}