我正在开发一个从数据库中提取数据的小型 Java 库。
假设有一个通用的Java 类:
公共类 MyClass {
public int valueA;
public String valueB;
public Double valueC;
//getter and setter methods.
}
之后,我定义了一个 SQL 查询字符串,并获得了泛型类的类MyClass
。
String sql = "Select c.valueA, c.valueB, c.valueC from my_table c";
Class<MyClass> type = MyClass.class;
List<MyClass> results = extractData(sql, type)M
该方法extractData
类似于以下方法:
public<T> List<T> extractData(String sql, Class<T> type){
//1)Do everything that is necessary to retrieve a ResultSet by the sql String.
//2)Then, for each row in the ResultSet
//2.1)Create a new instance of object of type T.
//2.2)Automatically matches the field name from the query
// with the field name of the specified class.
//2.3) add the object to the list to be returned.
//3) return the list of results of type T.
}
在实践中,如果可能的话,我该如何实施步骤 2.2?
我想这是可能的,因为我在 PHP 框架中使用了这种方法。