egoteclaier
egoteclaier

Reputation: 36

Java Hashmap to Object while running

Is there any way to cast the value of a Java HashMap to an Object at runtime like this:

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
}

I tryed to parse a SQL-Query result to a object. Now i've written my own Seralize-Algorithm. Bot it doesn't work. Is there a better way to Unerialize Object from the Database?

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();
        }
    }
}

Upvotes: 1

Views: 2684

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500055

It sounds like what you're actually trying to ask is:

Is there any way of accessing a variable dynamically by name at execution time?

To which the answer is "yes, but it's usually a bad idea".

You can use reflection:

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

But it will be slow, and you'll only find out about invalid keys/values at execution time. It's generally a bad idea. If you only know things dynamically, you can keep them dynamic - keep them in the map. If you want to store arbitrary properties, there's usually a better way of approaching the problem (e.g. custom serialization) but without more details, we can't help you work out that better way.

(Also note that you'll need Map.Entry<String, Object>, not Map.Entry<Foo, Bar> for your entry variable.)

Upvotes: 9

Related Questions