Search code examples
javareflectionjavabeansjava-bytecode-asm

How To Populate A JavaBean Other Than Using Reflection


do you know if there is anyway that I can populate a javabean but i don't want to use reflection.

For example I have this xml template to pouplate it

Sample XML File

<property name = "card" value = "cdd"/>

public class Customer {
    private String card;

     public void setCard(String card) {
          this.card = card;
     }

     public String getCard() {
     }

}

I want to call setCard on the Java bean but I don't want to use reflection since I've used it before and it's quite slow,

Are there any alternatives? How does Hibernate do it for example?

Thanks Carlo


Solution

  • The only faster way (i.e. faster than using reflection) to populate a JavaBean from XML is to either write or generate some binding code that calls the setters with values extracted from the XML (in this case, from the XML attributes).

    • Hand writing the binding code is the simplest approach ... provided you don't have much to write.

    • Code could be generated as source code and compiled.

    • Code could be generated using a bytecode generation technology such as BCEL or ASM.

    • There may some existing XML-to-JavaBean binding generator, though existing bindings may well use reflection rather than code generation.


    However, it is not clear this is worth going to the bother of avoiding reflection. While reflection is relatively expensive, XML is probably significantly more expensive. I'd recommend doing some profiling before you decide to use a more complicated implementation approach.