将光标移到/点击文章中的句子上,可以查看译文。      显示繁体中文内容    显示简体中文内容

What is a JavaBean exactly?
JavaBean到底是什么?

I understood, i think, that a"Bean"is a Java class with properties and getters/setters.as much as i understand, it is the equivalent of a C struct.is that true?

Also, is there a real syntactic difference between a bean and a regular class?is there any special definition or an interface?

Basically, why is there a term for this, it puzzles me...

Edit : if you can be so kind and add information regarding the Serializable interface, and what it means, to your answer, i'd be very grateful.

时间:

A JavaBean is just a standard

  1. All properties private (use getters/setters )
  2. A public no-argument constructor
  3. Implements Serializable.

That's it. it's just a convention.Lots of libraries depend on it though....

With respect to Serializable, from the API documentation :

Serializability of a class is enabled by the class implementing the java.io.Serializable interface.Classes that do not implement this interface will not have any of their state serialized or deserialized.all subtypes of a serializable class are themselves serializable.the serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

In other words, serializable objects can be written to streams, and hence files, object databases, anything really.

Also, there is no syntactic difference between a JavaBean and another class -- a class defines a JavaBean if it follows the standards.

There is a term for it because the standard allows libraries to programmatically do things with class instances you define in a predefined way.for example, if a library wants stream any object you pass into it, it knows it can because your object is serializable (assuming the lib requires your objects be proper JavaBeans).

Properties of JavaBeans

A JavaBean is a Java object that satisfies certain programming conventions :

  1. The JavaBean class must implement either Serializable or Externalizable

  2. The JavaBean class must have a no-arg constructor

  3. All JavaBean properties must have public setter and getter methods

  4. All JavaBean instance variables should be private

Example of JavaBeans


@Entity
public class Employee implements Serializable{

 @Id
 private int id;
 private String name; 
 private int salary; 

 public Employee() {}

 public Employee(String name, int salary) {
 this.name = name;
 this.salary = salary;
 }
 public int getId() {
 return id;
 }
 public void setId( int id ) {
 this.id = id;
 }
 public String getName() {
 return name;
 }
 public void setName( String name ) {
 this.name = name;
 }
 public int getSalary() {
 return salary;
 }
 public void setSalary( int salary ) {
 this.salary = salary;
 }
}

...