What is the advantage of using Java Beans?

Viewed 16303

I believe I understand what Java Beans are: Java class(es) which contain a no-arg constructor, are serializable, and expose their fields with getters and setters.

  1. Does a Java Bean have to expose all of its fields in order to qualify as a bean? If no, does it even have to expose any?

  2. May Java Beans include constructors with arguments as well as a no-arg constructor?

  3. What is the purpose of Java Beans, other than to conform to a certain coding style? It seems there is a lot of talk about 'beans this' or 'beans that', but I don't know why they are advantageous, specifically.

I can totally get making the no-arg constructor. There can be a slew of reasons for it, and I wouldn't be surprised if a no-arg constructor helps the compiler do some optimizations, either. I can also understand making your class serializable. Even if the class is never serialized, it could be, and going back to do it retroactively could be annoying (or impossible in a black-boxed library).

But most curious is the requirement to have fields all accessible via getters and setters. I do use them in my own work when I have need of them, but it seems odd that Java Beans requires them (possibly all of them, depending on my answer to #1). If it's an issue with reflection, couldn't the reflection get the fields just as easily? If it's an issue with doing more than simply setting the value, couldn't the reflection use a getter/setter over a field if the method exists?

6 Answers

I guess biggest advantage of bean is that one can pass data (more or less) in the form of single object. There is no need to make a lot of parameters in the definition of a method, rather one can use bean instead and pass data in the form of object directly. It provides better architecture of the programme...Thats what I think

Related