What is Java Bean

Just looking at the annotations in java, I always say that the annotations introduce a java bean, then I have to ask, what is a Java Bean?

Knowing the reference: https://www.zhihu.com/question/19773379 under Yang Bo's answer

The Java language lacks properties, events, and multiple inheritance. Therefore, if you want to implement some common requirements of object-oriented programming in a Java program, you can only write a lot of glue code. Java Beans are the idiomatic patterns or conventions for writing this glue code. These conventions include getXxx, setXxx, isXxx, addXxxListener, XxxEvent, etc. Classes that adhere to the above conventions can be used in several tools or libraries.

For example, if someone were to implement a singly linked list class in Java, they might write:

// 编译成 java-int-list_1.0.jar
public final class JavaIntList { static class Node { public Node next; public int value; } public Node head; public int size; } 

The above implementation caches the size of the linked list in the size variable in order to quickly obtain the size of the linked list. The usage is as follows:

JavaIntList myList = new JavaIntList(); System.out.println(myList.size); 

The author of JavaIntList was very satisfied, so he open sourced version 1.0 of the java-int-list library. The file name is java-int-list_1.0.jar. After its release, it attracted many users to use java-int-list_1.0.jar.
One day, the author decided to save memory, not to cache the size variable, and changed the code to this:

// 编译成 java-int-list_2.0.jar
public final class JavaIntList { static final class Node { public Node next; public int value; } public Node head; public int getSize() { Node n = head; int i = 0; while (n != null) { n = n.next; i++; } return i; } } 

Then version 2.0 was released: java-int-list_2.0.jar. After the release, users of the original java-int-list_1.0.jar upgraded to version 2.0 one after another. As soon as these users upgraded, they found that all their programs were broken, saying that they could not find any size variables. So these users beat the author and never dared to use the java-int-list library again.

The story tells us that if you don't want to be beaten to death, you have to maintain backward compatibility. Sun also understood this when designing the Java language. Therefore, in the Java standard library, there is absolutely no code such as public int size, but it must be written as:

private int size;
public int getSize() { return size; } 

Have the user use getSize from the start so that the getSize implementation is modified someday without breaking backwards compatibility. This idiom of public int getSize() { return size; } is Java Bean.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325043623&siteId=291194637