62,621
社区成员
发帖
与我相关
我的任务
分享
public class ConfigInDB {
public static int testA = 123, testB = 3;
public static String testC = "";
public static String print() {
return "testA:" + testA + ",testB:" + testB + ",testC:" + testC;
}
}
public static void loadConfigInDB() {
Class<ConfigInDB> configInDB = ConfigInDB.class;
// Field field = config.getField(pair.key);
Map<String, String> configs = new JavaDemoConfigDAO().queryAll();
log.debug(ConfigInDB.print());
if (configs != null && configs.size() > 0) {
for (Map.Entry<String, String> conf : configs.entrySet()) {
String key = conf.getKey();
String value = conf.getValue();
try {
Field field = configInDB.getField(key);
// Method m = configInDB.getMethod("set" + changeFirst(field.getName()),
// field.getType());
// m.invoke(configInDB, ConvertUtils.convert(value, field.getType()));
field.set(configInDB, ConvertUtils.convert(value, field.getType()));
} catch (SecurityException e) {
log.error("error", e);
} catch (NoSuchFieldException e) {
log.error("error,no such param, please delete from DB", e);
} catch (IllegalArgumentException e) {
log.error("error", e);
// } catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
// } catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
log.debug(ConfigInDB.print());
}
while(rs.next()){
timeout = Integer.parseInt(rs.getString("timeout"));
frequency = Float.valueOf(rs.getString("frequency "));
cronname = rs.getString("cronname");
……
}
我习惯这么写,因为实际运用中key对应的value类型已经是确定的了,这里完全可以这样直接转化。while(rs.next()){
String cl1 = rs.getString(1);
String cl2 = rs.getString(2);
if (cl1.equals("timeout")) {
timeout = Integer.parseInt(cl1);
} else if (cl1.equals("frequency")) {
frequency = Float.valueOf("cl1");
}
。。。
}
就这个思路,根据第一列的列值,判断第二列的数据类型,然后拿到自己想要的数据信息int timeout;
float frequency;
String cronname;
while(rs.next()){
//问题来了,获取的KEY也是个字符串,怎么对应到上面几个变量?
rs.getString("KEY");//这个是什么???
rs.getString("VALUE");
}
反射?