简体   繁体   English

返回与传入相同的接口实现的方法

[英]Method to return the same interface implementation as passed in

I've seen similar questions, but I don't really feel like I have an understanding of how to solve this.我见过类似的问题,但我真的不觉得我了解如何解决这个问题。 I want to make a method that takes a list of any class that implements an interface and returns an object of the same class.我想制作一个方法,该方法采用实现接口的任何类的列表并返回同一类的对象。

I was hoping something like this would work.我希望这样的事情会奏效。

public interface IHasDate {
  public Date getDate();
}

public class A implements IHasDate {
  private Date date;
  public Date getDate(){ return date; }
}

public class B implements IHasDate {
  private Date date;
  public Date getDate(){ return date; }
}

public class Util {
  public IHasDate getUpcoming(List<IHasDate> dates) {
    // logic omitted to find the object with the next upcoming date
    return dates.get(next);
  }
}

public class X {
  private List<A> aList;
  public A getUpcoming() {
    return Util.getUpcoming(aList);
  }
}

What I'm really trying to do is just avoid writing getUpcoming(List<?> aList) for each class that has a list of IHasDate's.我真正想做的是避免为每个具有 IHasDate 列表的类编写getUpcoming(List<?> aList)

Is there a better strategy for what I'm trying to do?对于我正在尝试做的事情,有更好的策略吗?

Right now I've been able to get around it by having a function that takes a list of IHasDate's and returns the index of the upcoming object in the list, but I have to create a new list of IHasDate's from aList first and it all just feels kind of clunky.现在我已经能够通过一个函数来绕过它,该函数接受 IHasDate 的列表并返回列表中即将到来的对象的索引,但我必须首先从 aList 创建一个新的 IHasDate 列表,这一切都只是感觉有点笨重。

What I was hoping for was something along these lines.我所希望的是这些方面的东西。

public T getUpcoming(List<T implements IHasDate> dates) {
  //...
}

You are sooo close.太近了

public <T extends IHasDate> T getUpcoming(List<T> dates) {
//...
}

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

相关问题 接口方法采用与接口相同的实现 - Interface method taking same implementation of interface 返回与传入参数相同的List实现 - Return same implementation of List as passed in parameter 返回给定接口的实现的工厂方法 - Factory method to return an implementation of a given Interface 当它们具有相同接口的相同实现时,将执行哪个方法? - Which method is getting executed when they have the same implementation of the same interface? 如果参数是同一接口的不同实现,则compareTo()应该返回什么? - What should compareTo() return if argument is different implementation of the same interface? 相同的接口,实现差异 - Same interface, implementation differences 接口实现隐藏方法 - Interface implementation hiding method Extends 和 Interface 具有相同的方法,但具有相同的参数但不同的返回类型 - Extends and Interface has same method with the same parameters but different return types java泛型方法的返回类型应该与传递的传递参数相同 - java generics return type of method should be same pass parameter passed 接口如何包含在其签名或返回类型中引用接口的具体实现类型的方法? - How can an interface include a method that references the concrete implementation type of the interface in its signature or return type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM