使用泛型类型调用方法时出现编译错误

时间:2015-10-14 17:09:05

标签: java oop generics jdbc

这将是一个非常愚蠢的问题,但我无法理解为什么在使用下面的代码时出现编译错误。我有一个像

这样的方法
public <T> List<T> mapGenericEntity(ResultSet resultSet, Class<T> type) throws SQLException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
     List<T> entities = new ArrayList<T>();
     while(resultSet.next()) {
        T instance = type.newInstance();
        for(Field field: type.getDeclaredFields()) {
            if(excludeFields.indexOf(field.getName()) != -1) {
                continue;
            }
            Object value = resultSet.getObject(field.getName());
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type);
            Method method = propertyDescriptor.getWriteMethod();
            method.invoke(instance, value);
        }
        entities.add(instance);
    }
    return entities;
}

我正在调用此方法,如下所示

mapGenericEntity(resultSet, Product.class);

但我收到编译错误如下

incompatible types: no instance(s) of type variable(s) T exist so that java.util.List<T> conforms to com.company.Product

我在这里缺少什么?

编辑:

解决方案

好的,所以我是傻瓜。 mapGenericEntity方法返回Product对象列表,我将它分配给单个实例。我正在做类似

的事情

Product product = mapGenericEntity(resultSet, Product.class);

但在Intellij中,下面有一个红色下划线

mapGenericEntity(resultSet, Product.class);

而不是

Product product

此外,错误消息应该更容易理解。

0 个答案:

没有答案
相关问题