What is a good use case for Java beans?

I just saw the Java beans specification I think using only getters, setters and empty constructors will make the code busier, and developers need to manage track to set all necessary instances correctly

Can anyone point out a good use case for using this design? I can't understand it I can think of a use – "when you need to create an instance of a class so that its data members can be determined later in the code."

Editor: guys, I'm not starting a discussion I don't want to discuss the advantages / disadvantages I'm not looking for current libraries like spring, which makes it necessary to use beans I am looking for an example to understand the engineering advantages of Java beans "Just an example of how Java beans design can help"

Solution

Many libraries and specifications (such as JPA, javael) use the Java beans specification and rely entirely on this behavior

The advantage of using getters and setters is that you can add code to these methods, such as creating "virtual" properties that are calculated at run time rather than stored in fields

In addition, using getters and setters allows other frameworks to wrap these methods and provide other functions, such as change logging In many cases, this is done by creating subclasses internally and overriding getters and setters The user will not notice because "weaving" or "proxy" is usually completed at run time For example, hibernate uses getter to provide deferred loading when you call getter to access related collections or entities

to update:

Upon request, an example of the virtual attribute:

Suppose you have a person bean whose fields are firstname and LastName You can add read-only virtual property names by providing the following getters:

public String getName() {
  return getFirstName() + " " + getLastName();
}

Update 2:

Another comment on why getters and setters are needed: this mainly comes from the working principle of Java Languages that directly support attributes, such as c#, allow you to write something like person Code of firstname = "Joe"; And if a setter still uses the setter, or if the property is read-only, an error is thrown Therefore, if you add a setter to firstname, these languages will internally convert firstname = "Joe" to setfirstname ("Joe"), and developers don't have to change anything - this is a very elegant solution

The above is a good use case of Java beans collected by programming house for you. What is it? I hope this article can help you solve a good use case of java bean? Program development problems encountered.

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>