如何使这个 Java 方法通用

How to make this Java method generic

我有一个 java 方法,我正在尝试使其通用,以便它可以将 2 种不同类型的对象列表作为参数。 (下面显示的简单示例)。这两个不同的对象都将始终具有 getDate() 和 getHour() 方法。代码如下所示:

public <T> List<T> getListOfStuff(List<T> statistics) {

    List<T> resultList = new ArrayList<T>(statistics.size());

    if(statistics.size() > 0){
        resultList.add(statistics.get(0));

        int date = Integer.parseInt(resultList.get(0).getDate());
        int hour = Integer.parseInt(resultList.get(0).getHour());
    }
    return resultList;
}

但是这不起作用。这两行不起作用:

int date = Integer.parseInt(resultList.get(0).getDate());
int hour = Integer.parseInt(resultList.get(0).getHour());

错误说: "The method getDate() is undefined for the type T" 和 "The method getHour() is undefined for the type T"

它向我提供了向方法接收器添加强制转换的建议,但它不允许我使用 T,而是像这样将对象名称强加给我,这对我不起作用:

int date = Integer.parseInt((ObjectName1)resultList.get(0).getDate());
int hour = Integer.parseInt((ObjectName1)resultList.get(0).getHour());

这里有什么方法可以做我想做的事吗?

您需要使用以下内容:

public <T extends ObjectName1> List<T> getListOfStuff(List<T> statistics) {
    List<T> resultList = new ArrayList<>(statistics.size());

    if (!statistics.isEmpty()) {
        resultList.add(statistics.get(0));

        int date = Integer.parseInt(resultList.get(0).getDate());
        int hour = Integer.parseInt(resultList.get(0).getHour());
    }

    return resultList;
}

现在唯一可以传递给此方法的 List 必须包含 ObjectName1 或扩展它的对象。

您的方法指定使用类型 T,所有编译器都知道它扩展了 ObjectObject 没有您调用的方法。您必须断言该类型具有您使用的方法。为此,您需要 <T extends Foo>,其中 Foo 是具有这些方法的类型。

ObjectName1 是最糟糕的类型名称之一。