我想弄清楚如何(如果它甚至可能)更改基類返回類型,當類型尚未傳遞給抽象類。 (我是這樣一個平淡無奇的解釋很抱歉,但我真的不知道如何更好地說明這一點)抽象超類傳遞超類型返回類型
// Base Profile and Repository
public abstract class BaseProfile { }
public abstract class BaseRepository<T extends BaseProfile> {
public abstract T doSomething(String name);
}
// Enhanced Profile and Repository
public abstract class EnhancedProfile extends BaseProfile {
public abstract String getName();
}
public abstract class EnhancedRepository<T extends EnhancedProfile> extends BaseRepository<T> {
}
// Instance of Repository
public class InstanceProfile extends EnhancedProfile {
@Override
public String getName() { return "Hello World"; }
}
public class InstanceRepository extends EnhancedRepository<EnhancedProfile> {
public EnhancedProfile doSomething() { return null; }
}
現在,我要的是存儲的EnhancedRepository不知道它的繼承類,並能夠訪問EnhancedProfile,不BaseProfile,見下圖:
// What I want
EnhancedRepository repo = new InstanceRepository();
EnhancedProfile enProfile = repo.doSomething();
// Does not work because the doSomething() method actually returns
// BaseProfile, when I need it to at least return the EnhancedProfile
// What I know works, but can't do
EnhancedRepository<InstanceProfile> repo2 = new InstanceRepository();
EnhancedProfile enProfile2 = repo2.doSomething();
// This works because I pass the supertype, but I can't do this because I need
// to be able to access EnhancedProfile from the doSomething() method
// from a location in my project which has no access to InstanceProfile
如何從DoSomething的()得到EnhancedProfile,而不是基最大的類型BaseProfile,不知道EnhancedRepository的超?
不要使用原始類型。使用通配符'>'來參數化'repo'。其下限是「EnhancedProfile」。 –