[英]How to make this Java method generic
I have a java method that i'm trying to make generic so that it can take a list of 2 different types of object as a parameter. 我有一个java方法,我试图使通用,以便它可以采取2种不同类型的对象的列表作为参数。 (Trivial example shown below).
(如下所示的琐碎例子)。 These 2 different objects will both always have the methods getDate() and getHour().
这两个不同的对象都将始终具有方法getDate()和getHour()。 The code looks like this:
代码如下所示:
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;
}
However this doesn't work. 但是这不起作用。 These two lines don't work:
这两行不起作用:
int date = Integer.parseInt(resultList.get(0).getDate());
int hour = Integer.parseInt(resultList.get(0).getHour());
The errors say: "The method getDate() is undefined for the type T" and "The method getHour() is undefined for the type T" 错误说:“方法getDate()未定义类型T”和“方法getHour()未定义类型T”
It offers me a suggestion to add a cast to the method receiver but it won't let me use T and instead forces the object name upon me like this which won't work for me: 它向我提出了向方法接收器添加强制转换的建议,但它不会让我使用T而是强制对象名称对我这样对我不起作用:
int date = Integer.parseInt((ObjectName1)resultList.get(0).getDate());
int hour = Integer.parseInt((ObjectName1)resultList.get(0).getHour());
Is there any way to do what I want here? 有什么方法可以做我想要的吗?
You'll want to use the following: 您将要使用以下内容:
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;
}
The only List
s that can be passed to this method now must either hold ObjectName1
or an object that extends it. 现在唯一可以传递给此方法的
List
必须包含ObjectName1
或扩展它的对象。
Your method specifies to use a type T
about which all the compiler knows is that it extends Object
. 您的方法指定使用类型
T
,所有编译器都知道它是扩展Object
。 Object
does not have the methods you invoked. Object
没有您调用的方法。 You have to assert that the type has the methods you use. 您必须断言该类型具有您使用的方法。 For that you need
<T extends Foo>
, where Foo
is a type with those methods. 为此,您需要
<T extends Foo>
,其中Foo
是具有这些方法的类型。
ObjectName1
is one of the worst names for a type possible. ObjectName1
是可能类型的最差名称之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.