How to quickly populate a Java object with data from another, unrelated object?

How can I start populating a simple Java object with data from any other arbitrary object?

For example, I might end up with an object Documentwhose child nodes I can iterate through, and I want to set the same property names in another object with node values.

I work mainly in dynamic languages, and I think I hung up on how this will work in perl or javascript, and will not be able to get my head out of the dynamic chute long enough to see it clearly.

I know I could do something like (pseudocode)

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

But it's just not very good, and it feels terrible when the number of properties or complexity increases.

In a dynamic language, I would do something like:

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

setField . , , , . ?

/ , java , Strings . enums ? </ >

, - , , .

.

+5
10

. , , String Java. .

" " , , , String Java " ". (), . :

this.fooBar = doc.get("fooBar");
this.bazQux = doc.get("bazQux");
// ... etc.

: " , sysBiz , . Just Work [tm]!" , Java - sysBiz, , sysBiz, . , , , , - zigBlog , (, - object.setField(key, val)), zigBlog.

, , , String Java - , - . , , , , , " " . , .

+3
+4

A XML XML B ?

, . XML . , , :)

+2

, MethodUtils apache ,

+1

, - Java - . , Java ! , Groovy , , -, .

EDIT: . . , . Java. Java. . - .

, Groovy:

// Assuming document implements Map.
document.each {

    // At this point, 'it' is a Map.Entry.
    // Make sure the property exists on the target object.
    if (object.properties.keySet().contains(it.key)) {

        // Set the property to the value from the map entry.
        object."${it.key}" = it.value
    }
}
+1

Java :

public interface Trasnformer<F, T>
{
    T transformFrom(F original);
}

:

public class IntegerStringTransofromer<Integer, String>
{
    public String transformFrom(Integer original)
    {
        // code
    }
}

, , , Java. , , . , perl, Java, ... , Java, perl, .

... m, y ... , , ( , )... , , , !

class Copier
{
    public static void copyFromTo(final Object source,
                                  final Object dest)
    {
        final Class   sourceClass;
        final Class   destClass;
        final Field[] sourceFields;

        sourceClass  = source.getClass();
        destClass    = dest.getClass();
        sourceFields = sourceClass.getDeclaredFields();

        for(final Field field : sourceFields)
        {
            copyField(field, source, dest, destClass);
        }
    }

    private static void copyField(final Field field,
                                  final Object source,
                                  final Object dest,
                                  final Class  destClass)
    {
        final String fieldName;
        final String methodName;

        fieldName  = field.getName();
        methodName = "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);

        try
        {
            final Method method;

            method = destClass.getMethod(methodName, field.getType());
            field.setAccessible(true);
            method.invoke(dest, field.get(source));
        }
        catch(final NoSuchMethodException ex)
        {
            // ignore it
            ex.printStackTrace();
        }
        catch(final IllegalAccessException ex)
        {
            // ignore it
            ex.printStackTrace();
        }
        catch(final IllegalArgumentException ex)
        {
            // ignore it
            ex.printStackTrace();
        }
        catch(final InvocationTargetException ex)
        {
            // ignore it
            ex.printStackTrace();
        }
    }
}

( , ).

public class Main
{
    public static void main(String[] args)
    {
        final B b;

        b = new B();
        Copier.copyFromTo(new A(), b);
        System.out.println("b.a = " + b.getA());
        System.out.println("b.b = " + b.getB());
        System.out.println("b.c = " + b.getC());
        System.out.println("b.d = " + b.getD());
        System.out.println("b.e = " + b.getE());
    }
}

class A
{
    private String a = "This";
    private String b = "Is";
    private String c = "A";
    private String d = "Bad";
    private String e = "Idea";
}

class B
{
    private String a;
    private String b;
    private String c;
    private String d;
    private String e;

    public void setA(final String val)
    {
        a = val;
    }

    public void setB(final String val)
    {
        b = val;
    }

    public void setC(final String val)
    {
        c = val;
    }

    public void setD(final String val)
    {
        d = val;
    }

    public void setE(final String val)
    {
        e = val;
    }

    public String getA()
    {
        return (a);
    }

    public String getB()
    {
        return (b);
    }

    public String getC()
    {
        return (c);
    }

    public String getD()
    {
        return (d);
    }

    public String getE()
    {
        return (e);
    }
}
+1

java.lang.reflect. () , . , "setFoo (...)", . . Java: -)

+1

Apache Commons BeanUtils - beans (, !)

- , unit test , - , . , XML- - JAXB.

, , , .

... , , , .

+1

apache beans (http://commons.apache.org/beanutils/), , , . , [copyProperties] [1] - , .

, , :

, , - , . getter, , , , , . setter, , .

, , - :

public class YourClass {
    public YourClass(
        @DynamicParameter(name = "id") String id,
        @DynamicParameter(name = "name") String name
    )
}

... , getParameterAnnotations. , beans .

, .

[1]: http://commons.apache.org/beanutils/v1.8.2/apidocs/org/apache/commons/beanutils/BeanUtils.html#copyProperties(java.lang.Object, java.lang.Object)

+1
+1

All Articles