次のように、実行時にJava HashMapの値をオブジェクトにキャストする方法はありますか?
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-Query の結果をオブジェクトに解析しようとしました。これで、独自の Seralize-Algorithm を作成できました。ボットは機能しません。データベースからオブジェクトを非シリアル化するより良い方法はありますか?
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();
}
}
}