当我还没有将类型传递给抽象类时,我试图弄清楚如何(如果它甚至可能)更改基本返回类型。 (我很抱歉这么简单的解释,但我真的不知道如何更好地解释这个)
// 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()而不是最基本类型的BaseProfile获取EnhancedProfile?
答案 0 :(得分: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("");
}