代码:
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
不太會排版,湊合看。
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
你的反射其實有點問題:
即使要取得class對象,最好不要透過Class.formName,除非你確實是需要動態載入外部類別。
不知道這樣寫是否符合你的要求
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;