【问题标题】:Abstract superclass passing supertype to return type抽象超类将超类型传递给返回类型
【发布时间】: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?

【问题讨论】:

  • 不要使用原始类型。使用通配符 &lt;?&gt; 参数化您的 repo。它的下界是EnhancedProfile

标签: java generics supertype


【解决方案1】:

一种简单的方法是不使用泛型(在您的示例中似乎毫无意义)。而是用更具体的方法覆盖该方法

// 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("");
}

【讨论】:

  • 我的示例是从我构建的更复杂的存储库中剥离出来的。如果没有泛型,我实际使用的 BaseRepository 将无法构建开发人员需要的特定类型的配置文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多