开发者

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


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.


I'm pretty sure Hibernate uses reflection APIs deep under the hood. Groovy also has some nice support for automatically generating and using bean getters/setters which also ultimately use reflection under the hood as well.

Now there is an option where you could hard code your parser to read the xml and call the appropriate setter given the name attribute, but you run into the problem of your parser becoming brittle (when your model changes if that makes sense).


If the Bean is your's you may implement an interface like this:

/** Tries to set the property named key with the value given and returns true for success or false otherwise. */
boolean set(String key, Object value);

Then simply cast to that interface and try to use that method to set the properties. It sure needs some work in the bean - but avoids reflection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜