简体   繁体   English

在接口方法中声明子类型捕获

[英]Declaring subtype captures in an interface method

I am basically trying to achieve the following syntax (currently, doesn't compile).我基本上试图实现以下语法(目前,不编译)。 If someone can explain how to achieve this, I would appreciate it.如果有人可以解释如何实现这一点,我将不胜感激。 Complicating matters is I have the 'add' method overloaded repeatedly使问题复杂化的是我反复重载了“添加”方法

public interface Organization {
    Organization add(Hub hub);
}

public class JpaOrganization implements Organization {


    @OneToMany(mappedBy = "organization", cascade = CascadeType.ALL)
    private Set<JpaHub> hubs = new LinkedHashSet<>();


    @Override
    public JpaOrganization add(JpaHub hub) {
        hub.setOrganization(this);
        hubs.add(hub);
        return this;
    }
}

  public interface Hub {
    void setOrganization(Organization organization);
  }


public class JpaHub implements Hub {
    @Override
    public void setOrganization(JpaOrganization organization) {
        this.organization = organization;
    }
}

I am trying to do this to abstract a DAO layer away for an expected migration.我试图这样做是为了将 DAO 层抽象出来以进行预期的迁移。 So, all "JPA" implementations can assume they are dealing with JPA implementations, which is essential for all the reflection to work.因此,所有“JPA”实现都可以假设它们正在处理 JPA 实现,这对于所有反射的工作都是必不可少的。

I need to capture the types but the syntax for this particular arrangement evades me.我需要捕获类型,但这种特定安排的语法回避了我。

I have tried something like:我尝试过类似的事情:

<O extends Organization, H extends Hub> O foo(H hub);

implementation:执行:

   @Override
    public JpaOrganization add(Hub hub) {
        return this;
    }

And this compiles but gives me a checked warning which indicates to me I might be doing something wrong.这编译但给了我一个检查警告,向我表明我可能做错了什么。 Based on what I am reading I am not sure I can do this without some warnings.根据我正在阅读的内容,我不确定我是否可以在没有警告的情况下做到这一点。

Define the type variables at class level:在类级别定义类型变量:

public interface Organization<O extends Organization, H extends Hub> {
  O add(H hub);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM