为什么不可能在Java中创建通用填充方法?
我有以下课程:为什么不可能在Java中创建通用填充方法?,java,generics,Java,Generics,我有以下课程: abstract class DTO{ } class SubscriptionDTO extends DTO { } 以及以下通用方法: protected void fillList(ResultSet rs, ArrayList<? extends DTO> l) throws BusinessLayerException { SubscriptionDTO bs; try { while (rs.next()
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();
}
}
protectedvoid fillList(ResultSet rs,ArrayList您应该使用想象以下情况,使用Foo extends Bar
和Zoo extends Bar
List<Foo> fooList = new ArrayList<Foo>();
fooList.addAll(aBunchOfFoos());
aMethodForBarLists(fooList);
List-doulist=new-ArrayList();
愚蠢的人。addAll(abunchofoos());
阿米索德福巴勒斯(傻瓜主义者);
然后我们有了方法本身:
void aMethodForBarLists (List<? extends Bar> barList) {
barList.add(new Zoo());
}
void-aMethodForBarLists(List这应该有效,而且更简单:
protected void fillList( ResultSet rs, List<DTO> l ) throws BusinessLayerException
{
SubscriptionDTO bs;
try
{
while ( rs.next() )
{
//initialize bs object...
l.add( bs );
}
}
catch ( SQLException e )
{
e.printStackTrace();
}
protectedvoid fillList(结果集rs,列表l)引发BusinessLayerException
{
订阅bs;
尝试
{
while(rs.next())
{
//初始化bs对象。。。
l、 添加(bs);
}
}
捕获(SQLE异常)
{
e、 printStackTrace();
}
}要回答这个问题,我需要看看您如何初始化bs,至少是类型声明。我认为您无法按计划编写泛型方法,因为您需要知道bs对象的确切类型才能创建它。例如,new SubscriptionTo()或new DeliveryDTO()@javashlook-你说得对。Mmyer的解释很好,让我意识到这一点。看来我会继续使用原始解决方案来解决这类问题。或者