Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canonicalizing Java bean property names

Tags:

java

javabeans

I have a bunch of third-party Java classes that use different property names for what are essentially the same property:

public class Foo {
   public String getReferenceID();
   public void setReferenceID(String id);
   public String getFilename();
   public void setFilename(String fileName);
}

public class Bar {
   public String getRefID();
   public void setRefID(String id);
   public String getFileName();
   public void setFileName(String fileName);
}

I'd like to be able to address these in a canonicalized form, so that I can treat them polymorphically, and so that I can do stuff with Apache BeanUtils like:

PropertyUtils.copyProperties(object1,object2);

Clearly it would be trivial to write an Adapter for each class ...

public class CanonicalizedBar implements CanonicalizedBazBean {
    public String getReferenceID() {
        return this.delegate.getRefID();
    }
    // etc.
}

But I wonder is there something out there more generalized and dynamic? Something that would take a one-to-many map of property name equivalences, and a delegate class, and produce the Adapter?

like image 498
slim Avatar asked Jun 19 '12 09:06

slim


3 Answers

I've never used it, but I think you're looking for 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.

Dozer not only supports mapping between attribute names, but also automatically converting between types. Most conversion scenarios are supported out of the box, but Dozer also allows you to specify custom conversions via XML.

like image 112
JB Nizet Avatar answered Oct 15 '22 20:10

JB Nizet


  1. First Option is Dozer.

  2. Second option is Smooks Framework with a tweak. It will be beneficial to use Smook's Graphical mapper.

  3. Another option would be XStream with custom Mapper.

like image 4
Puspendu Banerjee Avatar answered Oct 15 '22 20:10

Puspendu Banerjee


maybe something like that:

public class CanonicalizedBar implements CanonicalizedBazBean {
public String getReferenceID() {
    Method m = this.delegate.getClass().getDeclaredMethod("getReferenceID");
    if(m == null)
        m = this.delegate.getClass().getDeclaredMethod("getRefID");
    ...
    return m.invoke();
}
// etc.
}
like image 2
nidomiro Avatar answered Oct 15 '22 20:10

nidomiro