首页 > 解决方案 > 如何在运行时动态创建对象 T?

问题描述

因此,我尝试对每个操作仅使用一种方法来实现一些 CRUD 操作。
所以我有这个实体:

@Table(name = "CLIENT")
public class Client {

    @Column(name = "ID", isPrimaryKey = true)
    private long id;

    @Column(name = "FULL_NAME")
    private String name;

    @Column(name = "MONEY")
    private double money;

    public void setId(long id) { this.id = id; }

    public long getId() { return id; }

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public void setMoney(double money){
        this.money = money;
    }

    public double getMoney(){
        return money;
    }
}

在运行时,我想从数据库中获取一个客户端,使用反射创建一个查询。我根据类型 T 创建此查询,结果将进入 ResultSet。现在,问题是,我如何设法在运行时创建对象 T 并使用 setter 插入属性?我真的不知道这种方式是否正确,但我想通过反射和使用注释来实现这一点。

public final Optional<T> get(long id) {

        //after fetching the class of T, I insert the class to dynamically
        //create the query based on reflection using the annotations
        Query creator = new SelectQuery(class);
        String query = creator.getQuery();
        try {
            pstmt = connection.prepareStatement(query);
            pstmt.setLong(1,id);
            rs = pstmt.executeQuery();

            //What to do here?
            while(rs.next()){
                T t = (T) classOfT.getConstructor(null).newInstance();
            }
        } catch (SQLException throwables) {
            System.err.println("An error has occured while trying to get an object in get method!");
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return null;
    }

标签: javajdbc

解决方案


推荐阅读