我有以下类(class):
abstract class DTO{ }
class SubscriptionDTO extends DTO { }
和以下通用方法:
protected void fillList(ResultSet rs, ArrayList<? extends DTO> l)
throws BusinessLayerException {
SubscriptionDTO bs;
try {
while (rs.next()){
//initialize bs object...
l.add(bs); //compiler error here
}
} catch (SQLException e) {
e.printStackTrace();
}
}
我似乎无法理解为什么您不能创建一个通用方法来填充 DTO 子类型。我做错了什么还是设计使然?如果是这样,是否有任何解决方法?提前致谢。
最佳答案
你应该使用 <? super DTO>
(或 <? super SubscriptionDTO>
,如 Tom Hawtin - tackline 指出的那样)作为 ArrayList
的通用参数.
来自 Effective Java 的第 28 项(sample chapter [pdf] 第 28 页):
Here is a mnemonic to help you remember which wildcard type to use:
PECS stands for producer-extends, consumer-super.
In other words, if a parameterized type represents a
T
producer, use<? extends T>
; if it represents aT
consumer, use<? super T>
.
在这种情况下,l
是消费者(您将对象传递给它),所以 <? super T>
类型合适。
关于java - 为什么不能在 Java 中创建通用填充方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/820840/