有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带通配符的Java接口?

我需要编写一个接口,该接口将用于至少两种不同的实现,如以下示例:

public interface AsdDAO{
    public Set<_What_?> getEntities();
}

public class AsdPlayerDao implements AsdDAO{
   public Set<Player> getEntities();
}

public class AsdPartnerDao implements AsdDAO{
   public Set<Partner> getEntities();
}

这些类将用于检索实体集合,如下所示:

@Autowired
AsdPartnerDao dao;

public void method(){
    Set<Partner> partners = dao.getEntities();
    //Some other stuff
}

这里是否可以使用通配符,比如public Set<?> getEntities();。我的问题是,实际上如何编写接口是最好的方法


共 (2) 个答案

  1. # 1 楼答案

    如果实体未实现公共接口:

    public interface AsdDAO{ public Set<?> getEntities(); }

    如果有:

    public interface AsdDAO{ public Set<? extends YourInterface> getEntities(); }

  2. # 2 楼答案

    看起来你想要

    public interface AsdDAO<T>{
        public Set<T> getEntities();
    }
    
    public class AsdPlayerDao implements AsdDAO<Player>{
       public Set<Player> getEntities();
    }
    
    public class AsdPartnerDao implements AsdDAO<Player>{
       public Set<Partner> getEntities();
    }
    

    例如,也可以约束类型

    public interface AsdDAO<T extends SomeInterfaceYouHave>{