2016-06-01 140 views
0

我想弄清楚如何(如果它甚至可能)更改基類返回類型,當類型尚未傳遞給抽象類。 (我是這樣一個平淡無奇的解釋很抱歉,但我真的不知道如何更好地說明這一點)抽象超類傳遞超類型返回類型

// 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的超?

+0

不要使用原始類型。使用通配符''來參數化'repo'。其下限是「EnhancedProfile」。 –

回答

0

一個簡單的方法是不使用泛型(在你的例子中似乎毫無意義)。而是用一個更具體的覆蓋方法

// Base Profile and Repository 
public abstract class BaseProfile { 
} 

public abstract class BaseRepository { 
    public abstract BaseProfile doSomething(String name); 
} 

// Enhanced Profile and Repository 
public abstract class EnhancedProfile extends BaseProfile { 
    public abstract String getName(); 
} 

public abstract class EnhancedRepository extends BaseRepository { 
    @Override 
    public abstract EnhancedProfile doSomething(String name); 
} 

// Instance of Repository 
public class InstanceProfile extends EnhancedProfile { 
    @Override 
    public String getName() { 
     return "Hello World"; 
    } 
} 

public class InstanceRepository extends EnhancedRepository { 
    public EnhancedProfile doSomething(String name) { 
     return null; 
    } 
} 

void whatIWant() { 
    EnhancedRepository repo = new InstanceRepository(); 
    EnhancedProfile enProfile = repo.doSomething(""); 
} 
+0

我的示例從我建立的更復雜的存儲庫中剝離下來。沒有泛型,我實際使用的BaseRepository將無法構建開發人員需要的特定類型的配置文件。 –