我们设法创建了一个Store类
public class Store<T> {
private T value;
public void set(T object){
value = object;
}
public T get(){
return value;
}
}
并修改您的 GenericClass
public class GenericClass{
public <T> void storeGenericClass(Store<T> store, Class<T> clazz){
String sql = "SELECT field1, field2 FROM MYTABLE WHERE ID = 1";
try(org.sql2o.Connection con = sql2o.open()) {
store.set(con.createQuery(sql).executeAndFetchFirst(clazz));
}
}
public <T> void storeGenericClass(List<T> store, Class<T> clazz){
String sql = "SELECT field1, field2 FROM " +
clazz.getName().toUpperCase();
try(org.sql2o.Connection con = sql2o.open()) {
store.addAll(con.createQuery(sql).executeAndFetch(clazz));
}
}
}
使用与 tableName 相同的 className 不是最佳做法。但是如果你用一张表来映射每个类,你可以这样做
public class GenericClass{
...
public <T> void storeGenericClass(List<T> store, Class<T> clazz){
String sql = "SELECT field1, field2 FROM " +
clazz.getName().toUpperCase();
try(org.sql2o.Connection con = sql2o.open()) {
store.addAll(con.createQuery(sql).executeAndFetch(clazz));
}
}
...
}
实例化:
public class MyClass {
public String field1, field2;
}
...
GenericClass generic= new GenericClass(sql2o);
Store<MyClass> store = new Store<>();
generic.storeGenericClass(store, MyClass.class);
MyClass retrieved = store.get();
System.out.println("My Class fields are: "+retrieved.field1 + "-"+retrieved.field2);
...