有没有办法在运行时将 Java HashMap 的值转换为 Object,如下所示:
claas Foo {
public int a;
public String b;
}
Foo foo = new Foo();
HashMap<String, Object> map = new HashMap<String, Object>();
for(Map.Entry<Foo, Bar> entry : map.entrySet()) {
String propertyName foo = entry.getKey();
Object o = entry.getValue();
foo[propertyName] = o; // Does not wokring
}
我试图将 SQL 查询结果解析为对象。现在我已经编写了自己的 Seralize 算法。机器人它不起作用。有没有更好的方法从数据库中反序列化对象?
Connection connection = DriverManager.getConnection(instance);
PreparedStatement statment = connection.prepareStatement("SELECT * FROM Foo;");
Foo data;
ResultSet rs = statment.executeQuery(query);
if (rs != null && rs.next()) {
for (Field field : data.getClass().getDeclaredFields()) {
try {
if ((String.class.equals(field.getType()))) {
field.set(String.class, rs.getString(field.getName()));
} else if ((Boolean.class.equals(field.getType()))) {
field.set(Boolean.class, rs.getBoolean(field.getName()));
} else if ((Integer.class.equals(field.getType()))) {
field.set(Integer.class, rs.getInt(field.getName()));
}
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}