1

次のように、実行時に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();
        }
    }
}
4

1 に答える 1

9

あなたが実際に尋ねようとしているのは次のようです。

実行時に名前で動的に変数にアクセスする方法はありますか?

答えは「はい、しかしそれは通常は悪い考えです」.

リフレクションを使用できます:

Field field = Foo.class.getDeclaredField(entry.getKey());
field.set(foo, entry.getValue());

しかし、それは遅く、実行時に無効なキー/値についてのみ知ることができます。それは一般的に悪い考えです。物事を動的にしか知らない場合は、それらを動的に保つことができます-マップに保持します。任意のプロパティを保存したい場合は、通常、問題に対処するためのより良い方法 (カスタム シリアライゼーションなど) がありますが、それ以上の詳細がなければ、その方法を改善することはできません。

(また、変数Map.Entry<String, Object>ではなくが必要になることに注意してください。)Map.Entry<Foo, Bar>entry

于 2013-02-12T18:58:56.797 に答える