java - 如何在运行时动态创建对象 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;
}
解决方案
推荐阅读
- mysql - 使用 RefreshDatabase 特征时如何跳过某些迁移文件
- java - 即使在 Java 中类型擦除之后,JSON 如何映射到 List<>
- reactjs - useState 返回空数组
- c++ - 如何正确地将颜色顶部的纹理与透明度混合?
- c - 将文件名作为参数传递给 fopen() 不起作用
- javascript - 如何动态设置图形折线图?
- docker - 弹性容器服务上的“sh: 1: ./binary: Permission denied”
- swift - 如何快速加载标签每秒?
- html - 空值正在使用 express 返回数组
- stripe-payments - Stripe Payment Link 成功链接以包含会话 ID