代码:
public static List<Object> select(String sql, String o)
throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
Class c = Class.forName(o);
Field[] fls = c.getDeclaredFields();
List<String> list= new ArrayList<>();
for (int i = 0; i < fls.length; i++) {
System.out.println("公有属性之" + fls[i].getName());
list.add(fls[i].getName());
}
Object object = c.newInstance();
List<Object> l = new ArrayList<>();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
// Retrieve by column name
String id = rs.getString("href");
String name = rs.getString("title");
// Display values
System.out.print("ID: " + id);
System.out.print(", name: " + name);
}
rs.close();
stmt.close();
conn.close();
return l;
}
我想获取传进来的类的所有属性,然后通过re.getString获得值,但是我不知道属性有多少个,在rs.next里for循环遍历的话就会失去rs的作用域。麻烦哪位大神帮我看看怎么写 = =。
I’m not very good at typesetting, so I can just read it.
There is actually a problem with your reflection:
Even if you want to get the class object, it is best not to pass Class.formName, unless you really need to dynamically load external classes.
I don’t know if writing like this meets your requirements
org.springframework.jdbc.core.BeanPropertyRowMapper
Ready-made implementation, you can refer to it and imitate it.