简体   繁体   中英

How to write a Helper class to map classes to each other in Java?

There is a question on my mind for a while. Let's say we have the following classes:

public Class Person{
    String name;
    String address;
    String description;
}

public Class PersonFacade{
    String name;
    String address;
    String desc;
}

as you can see the only difference between these two classes are the name of one variable. My question is what is the best way to write a helper class to map the values of one object to another object. Let's assume we have the following:

Person person = new Person();
person.name="name1";
person.address="address1";
person.description="description1";

I want to write a class that is supposed to do the following (let's call it Transformer class)

PersonFacade personFacade = new PersonFacade();
TransformClass.transformFrom(person, personFacade);

What I want this TransformClass.transformFrom() method to do is the follwoing:

based on the similarity of the variable names, assign the value of the variable from "FromClass" to "ToClass" so in our case, I want it to assign personFacade.name = "name1" , personFacade.address="adderss1" and personFacade.desc = "description1" (this last one seems harder to accomplish, but let's try)

Any ideas?

You can use Dozer :

Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.

Dozer supports simple property mapping, complex type mapping, bi-directional mapping, implicit-explicit mapping, as well as recursive mapping. This includes mapping collection attributes that also need mapping at the element level.

Look at this: http://dozer.sourceforge.net/

It's a great JavaBean Mapper.

Here the "Getting Started":

http://dozer.sourceforge.net/documentation/gettingstarted.html

Perhaps you can write your own Annotation class in order to create the relationship between the classes. So, for example

public Class Person{
    @MyAnnotation(id='name')
    String name;

    @MyAnnotation(id='addr')
    String address;

    @MyAnnotation(id='desc')
    String description;
}

public Class PersonFacade{
    @MyAnnotation(id='name')
    String name;

    @MyAnnotation(id='addr')
    String address;

    @MyAnnotation(id='desc')
    String desc;
}

Then in your TransformClass, you simply need to iterate through the annotations, find a match and set the corresponding field value with the help of Reflection .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM