【发布时间】:2016-06-01 02:43:03
【问题描述】:
当类型尚未传递给抽象类时,我试图弄清楚如何(如果可能的话)更改基本返回类型。 (我很抱歉这么平淡的解释,但我真的不知道如何更好地解释这一点)
// 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
在不知道 EnhancedRepository 的超类型的情况下,如何从 doSomething() 获取 EnhancedProfile,而不是最基础的类型 BaseProfile?
【问题讨论】:
-
不要使用原始类型。使用通配符
<?>参数化您的repo。它的下界是EnhancedProfile。