0

我正在尝试使用ResultSet从 DataBase创建基于PropertyDescriptor的列表对象实例。问题是即使在 PropertyDescriptor 中类和字段匹配,我也会得到IntrospectionException 。

这是失败的行:PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), model.Client.class);

这是我得到异常的代码:

public class Dao<T> {
    private final Class<T> type;
    @SuppressWarnings("unchecked")
    public Dao() {
        this.type=(Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0] ;
        //this.type= (Class<T>) getClass();
    }
    private List<T> createObjects(ResultSet resultSet)
    {
        List<T> list = new ArrayList<T>();
        try {
            while(resultSet.next())
            {
                System.out.println(type.getSimpleName());
                T instance = type.getDeclaredConstructor().newInstance();
                for(Field field : type.getDeclaredFields())
                {
                    Object value = resultSet.getObject(field.getName());
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type); // Exception is here
                    Method method = propertyDescriptor.getWriteMethod();
                    method.invoke(instance,value);
                }
                list.add(instance);
            }
        } catch (SQLException | InstantiationException | IllegalAccessException | IntrospectionException | InvocationTargetException | NoSuchMethodException  throwables) {
            throwables.printStackTrace();
        }
        return list;
    } }

当我尝试执行以下语句时,我使用了许多其他类的Client类,以及扩展了 Dao 的ClientDao 。

这是Client类,它将用于使用泛型类提取字段

package model;
public class Client {
    private int idc;
    private String tel;
    private String username;
    public Client(int idc,String username,String tel)
    {
        this.idc=idc;
        this.username=username;
        this.tel=tel;
    }
    public Client()
    {

    }
    public void setIdc(int idc) {
        this.idc = idc;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
}

这是用于将泛型与Client类映射的类。

package dataAccess.connection;
import model.Client;
public class ClientDao extends Dao<Client> {
    public ClientDao()
    {
        super();
    }
}

以及方法的调用。

 ClientDao client =new ClientDao();
 List<Client> list=client.createObjects(resultSet);

可能是什么问题呢?我检查了 field.getName() 和类型,它们应该根据 Client 类匹配

4

0 回答 0