Rumah > Soal Jawab > teks badan
代码:
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的作用域。麻烦哪位大神帮我看看怎么写 = =。
PHP中文网2017-04-18 10:30:16
Saya tidak begitu mahir dalam menaip, jadi saya boleh membacanya sahaja.
while(rs.next()){
//cls: Class<T> cls
T t=cls.newInstance();
//rsmd: ResultSetMetaData rsmd
for(int i=0;i<rsmd.getColumnCount();i++){
errorIndex=i+1;
String columnName=(rsmd.getColumnName(i+1)).toLowerCase();
//rs: ResultSet rs
Object obj=rs.getObject(columnName);
if(null==obj) continue;
columnName=String.valueOf(columnName.charAt(0)).toUpperCase()+columnName.substring(1);
Method m;
m=cls.getMethod("set"+columnName, obj.getClass());
m.invoke(t, obj);
}
dataList.add(t);
}
高洛峰2017-04-18 10:30:16
Sebenarnya terdapat masalah dengan refleksi anda:
Walaupun anda ingin mendapatkan objek kelas, sebaiknya jangan lulus Class.formName, melainkan anda benar-benar perlu memuatkan kelas luaran secara dinamik.
Saya tidak tahu sama ada menulis dengan cara ini memenuhi keperluan anda
public static List<Map<String,Object>> select(Object o)
throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
Field[] fds=o.getClass().getDeclaredFields();
String[] names=new String[fds.length];
for(int i=0;i<fds.length;i++){
names[i]=fds[i].getName();
System.out.println(names[i]);
}
List<Map<String,Object>> list=new ArrayList<>();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Map<String,Object> m=new HashMap<>();
for(String name:names){
String tmp = rs.getString(name);
m.put(name, tmp);
}
list.add(m);
}
rs.close();
stmt.close();
conn.close();
return list;
高洛峰2017-04-18 10:30:16
org.springframework.jdbc.core.BeanPropertyRowMapper
Pelaksanaan yang sudah siap, anda boleh merujuk dan menirunya.