How to quickly populate a Java object with data from another, unrelated object?
<p>How can I go about populating a simple Java object with data from any other arbitrary object?</p>

<p>For example, I can end up with a <a href="http://java.sun.com/j2se/1.4.2/docs/api/org/w3c/dom/Document.html" rel="nofollow"><code>Document</code></a> object whose children nodes I can iterate through and I want to set same-named properties in another object with the node's values.</p>

<p>I work primarily in dynamic languages and I think I am hung up on how this would work in perl or javascript and can't get my head out of the dynamic gutter long enough to see this clearly.</p>

<p>I know I could do something like (pseudo code)</p>

<pre><code>while (key = nextKey) {
    if (key.name == "fooBar") {
        object.setFooBar(key.value);
    } else if (key.name == "bazQux") {
        object.setBazQux(key.value);
    }
    ...etc...
}
</code></pre>

<p>But that just doesn't feel good, and feels awful when the number of properties or complexity increases.</p>

<p>In a dynamic language, i would do something like:</p>

<pre><code>while (key = nextKey) {
    object.setField(key.name, key.value);
    // or even
    object.[key.name] = key.value;
}
</code></pre>

<p>where <code>setField</code> could be a dispatch table with code references. I know I don't have the luxury of every object being a hash by default, but I'm looking for general advice. How would you do it?</p>

<p>A switch/case would be a little better, but java complains about it not enjoying Strings in such statements. Would enums be a solution? &lt;/blind stabbing for answers&gt;</p>

<p>I've looked into using reflection in order to implement some sort of automatic dispatch table, but that strikes me as being looked down upon and that there has to be a better way.</p>

<p>Thanks for any insight.</p>
