2016-06-01 134 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将无法构建开发人员需要的特定类型的配置文件。 –