我尝试构建一个通用方法,但我不知道如何转换它以及在 Java 中是否可能
这是原始方法
public List<PcsTTR> obtainAllPcsTttrRecords() throws Exception {
try {
TypedQuery<PcsTTR> pQuery = em.createNamedQuery("PcsTTR.findAll", PcsTTR.class);
return pQuery.getResultList();
} catch (Throwable t) {
throw new Exception("database error ", t);
}
}
我使用了工厂模式
public <T> List<T> obtainAllRecords(String tableName) throws Exception {
// if tableName = PcsTTR Im getting PcsTtr object
myEntity tableObj = myEntityFactory.getTableObj(tableName);
String tableObjName = table.getClass().getSimpleName();
try {
TypedQuery<T> pQuery = em.createNamedQuery(tableObjName+".findAll", ??????);
return pQuery.getResultList();
} catch (Throwable t) {
throw new Exception("database error " + tableNamee + " !" + t);
}
}
我不知道该用什么来代替“???”
最佳答案
您可以使用的一件事是 TypeToken这是 Gson 工件的一部分。
TypedQuery<T> pQuery = em.createNamedQuery(tableObjName+".findAll", new TypeToken<T>() {}.getRawType());
关于java - 获取具有类扩展的变量的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61364386/