Related
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 JavaBean and a regular class?
Is there any special definition or an Interface?
Basically, why is there a term for this?
Also what does the Serializable interface mean?
A JavaBean is just a standard. It is a regular Java class, except it follows certain conventions:
All properties are private (use getters/setters)
A public no-argument constructor
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 is 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 to stream any object you pass into it, it knows it can because your object is serializable (assuming the library requires your objects be proper JavaBeans).
There's a term for it to make it sound special. The reality is nowhere near so mysterious.
Basically, a "Bean":
is a serializable object (that is, it implements java.io.Serializable, and does so correctly), that
has "properties" whose getters and setters are just methods with certain names (like, say, getFoo() is the getter for the "Foo" property), and
has a public zero-argument constructor (so it can be created at will and configured by setting its properties).
As for Serializable: That is nothing but a "marker interface" (an interface that doesn't declare any functions) that tells Java that the implementing class consents to (and implies that it is capable of) "serialization" -- a process that converts an instance into a stream of bytes. Those bytes can be stored in files, sent over a network connection, etc., and have enough information to allow a JVM (at least, one that knows about the object's type) to reconstruct the object later -- possibly in a different instance of the application, or even on a whole other machine!
Of course, in order to do that, the class has to abide by certain limitations. Chief among them is that all instance fields must be either primitive types (int, bool, etc.), instances of some class that is also serializable, or marked as transient so that Java won't try to include them. (This of course means that transient fields will not survive the trip over a stream. A class that has transient fields should be prepared to reinitialize them if necessary.)
A class that can not abide by those limitations should not implement Serializable (and, IIRC, the Java compiler won't even let it do so.)
JavaBeans are Java classes which adhere to an extremely simple coding convention.
All you have to do is to
implement the java.io.Serializable interface - to save the state of an
object
use a public empty argument constructor - to instantiate the object
provide public getter/setter methods - to get and set the values of private variables (properties).
Properties of JavaBeans
A JavaBean is a Java object that satisfies certain programming conventions:
The JavaBean class must implement either Serializable or
Externalizable
The JavaBean class must have a no-arg constructor
All JavaBean properties must have public setter and getter methods
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;
}
}
Explanation with an example.
1. import java.io.Serializable
As for the Serialization, see the documentation.
2. private fields
Fields should be private for prevent outer classes to easily modify those fields.
Instead of directly accesing to those fields, usuagly getter/setter methods are used.
3. Constructor
A public constructor without any argument.
4. getter/setter
Getter and setter methods for accessing and modifying private fields.
/** 1. import java.io.Serializable */
public class User implements java.io.Serializable {
/** 2. private fields */
private int id;
private String name;
/** 3. Constructor */
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
/** 4. getter/setter */
// getter
public int getId() {
return id;
}
public String getName() {
return name;
}
// setter
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
Java Beans are used for a less code and more work approach...
Java Beans are used throughout Java EE as a universal contract for runtime discovery and access. For example, JavaServer Pages (JSP) uses Java Beans as data transfer objects between pages or between servlets and JSPs. Java EE's JavaBeans Activation Framework uses Java Beans for integrating support for MIME data types into Java EE. The Java EE Management API uses JavaBeans as the foundation for the instrumentation of resources to be managed in a Java EE environment.
About Serialization:
In object serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
You will find serialization useful when deploying your project across multiple servers since beans will be persisted and transferred across them.
Just a little background/update on the bean concept. Many other answers actually have the what but not so much why of them.
They were invented early on in Java as part of building GUIs. They followed patterns that were easy for tools to pull apart letting them create a properties panel so you could edit the attributes of the Bean. In general, the Bean properties represented a control on the screen (Think x,y,width,height,text,..)
You can also think of it as a strongly typed data structure.
Over time these became useful for lots of tools that used the same type of access (For example, Hibernate to persist data structures to the database)
As the tools evolved, they moved more towards annotations and away from pulling apart the setter/getter names. Now most systems don't require beans, they can take any plain old Java object with annotated properties to tell them how to manipulate them.
Now I see beans as annotated property balls--they are really only useful for the annotations they carry.
Beans themselves are not a healthy pattern. They destroy encapsulation by their nature since they expose all their properties to external manipulation and as they are used there is a tendency (by no means a requirement) to create code to manipulate the bean externally instead of creating code inside the bean (violates "don't ask an object for its values, ask an object to do something for you"). Using annotated POJOs with minimal getters and no setters is much more OO restoring encapsulation and with the possibility of immutability.
By the way, as all this stuff was happening someone extended the concept to something called Enterprise Java Beans. These are... different. and they are complicated enough that many people felt they didn't understand the entire Bean concept and stopped using the term. This is, I think, why you generally hear beans referred to as POJOs (since every Java object is a POJO this is technically OK, but when you hear someone say POJO they are most often thinking about something that follows the bean pattern)
JavaBeans is a standard, and its basic syntax requirements have been clearly explained by the other answers.
However, IMO, it is more than a simple syntax standard. The real meaning or intended usage of JavaBeans is, together with various tool supports around the standard, to facilitate code reuse and component-based software engineering, i.e. enable developers to build applications by assembling existing components (classes) and without having to write any code (or only have to write a little glue code). Unfortunately this technology is way under-estimated and under-utilized by the industry, which can be told from the answers in this thread.
If you read Oracle's tutorial on JavaBeans, you can get a better understanding in that.
For a Java class to be usable as a Java bean, its method names need to be as per the JavaBeans guidelines (also called design patterns) for properties, methods, and events. The class needs to be a public class to be accessible to any beanbox tool or container. The container must be able to instantiate it; with the class as public, the container should be able to do so even if no explicit, public, zero-args constructor is provided. (A Java public class with no explicit constructor has a default public zero-args constructor.) So, minimally, a Java public class, even with a property as the sole member (of course, accompanying public getter and setter required) or a public method as the sole member, is a Java bean. The property can either be a read-only property (it has a getter method but no setter) or write-only property (has a setter method only). A Java public class with a public event listener registration method as the sole member is also a Java bean. The JavaBeans specification doesn’t require that if such a Java class has an explicit public constructor, it should be a zero-args one. If one could provide a file (with an extension, say, .ser) containing a serialized instance, a beanbox tool may be able to use that file to instantiate a prototype bean. Otherwise, the class would need a constructor, either explicit or default, that is public as well as zero-args.
Once the bean is instantiated, the JavaBeans API ( java.beans.*) can introspect it and call methods on it. If no class implementing the interface BeanInfo or extending a BeanInfo implementation,such as the SimpleBeanInfo class, is available, the introspection involves using reflection (implicit introspection) to study the methods supported by a target bean and then applying simple design patterns(the guidelines) to deduce from those methods what properties, events, and public methods are supported. If a class implementing the interface BeanInfo (for a bean Foo, it must be named FooBeanInfo) is available, the API bypasses implicit introspection and uses public methods (getPropertyDescriptor(), getMethodDescriptors(), getEventSetDescriptors() ) of this class to get the information. If a class extending SimpleBeanInfo is available, depending on which of the SimpleBeanInfo public methods (getPropertyDescriptor(), getMethodDescriptors(), getEventSetDescriptors() ) are overridden, it will use those overridden methods(s) to get information; for a method that is not overridden, it’ll default to the corresponding implicit introspection. A bean needs to be instantiated anyway, even if no implicit introspection is carried out on it. Thus, the requirement of a public zero-args constructor. But, of course, the Serializable or Externalizable interface isn’t necessary for it to be recognized. However, the JavaBeans specification says, ‘We’d also like it to be “trivial” for the common case of a tiny Bean that simply wants to have its internal state saved and doesn’t want to think about it.’ So, all beans must implement Serializable or Externalizable interface.
Overall, the JavaBeans specification isn’t hard and fast about what constitutes a bean. "Writing JavaBeans components is surprisingly easy. You don't need a special tool and you don't have to implement any interfaces. Writing beans is simply a matter of following certain coding conventions. All you have to do is make your class look like a bean — tools that use beans will be able to recognize and use your bean." Trivially, even the following class is a Java bean,
public class Trivial implements java.io.Serializable {}
The description so far is the Java SE version (JavaBeans). The beans, as described below, are the Java EE versions. These versions have been built on the underlying ideas as explained above. In particular, one main idea they consider is what if a bean constructor does have some parameters. These parameters could be either simple types, class/interface types or both. There should be a way to let the container know values that it can substitute for the parameters when instantiating the bean. The way to do so is that the programmer can configure (specify values) by say annotations or XML configuration files or a mix of both.
Spring Beans
Spring beans run in a Spring IoC container. The programmer can configure via XML configuration files, annotations or a mix of both.
In Spring, if a bean constructor has simple-type or class/interface type parameters, values can be assigned as strings (as the <value> attribute of a constructor argument element in the former case and as an <idref> element of a constructor argument in the latter case) in a type-safe manner. Making references to other Spring beans (called collaborators; via the <ref> element in a constructor argument element) is basically dependency injection and is also typesafe. Obviously, a dependency (collaborator bean) might have a constructor with injected parameters; those injected dependency(ies) might have a constructor with parameters and so on. This scenario should ultimately terminate at injected dependency(ies) that are prototype beans that the container can instantiate by constructing.
JSF Managed Beans
JSF managed beans run in a web container. They can be configured either with the #ManagedBean annotation or with an application configuration resource file managed-bean.xml. The JSF spec supports injection via resource injection (not typesafe) only. This injection is not fit for injection on constructors. In any case, the spec requires that a JSF managed bean must have a public zero-argument constructor. Further it says, “As of version 2.3 of this specification, use of the managed bean facility as specified in this section is strongly
discouraged. A better and more cohesively integrated solution for solving the same problem is to use Contexts and Dependency Injection (CDI), as specified in JSR-365." In other words, CDI managed beans should be used, which do offer typesafe dependency injection on constructors akin to Spring beans. The CDI specification adopts the Managed Beans specification, which applies to all containers of the JEE platform, not just the web tier. Thus, the web container needs to implement the CDI specification.
Managed Beans
Here is an extract from the Managed Bean specification
“ Managed Beans are container-managed objects with minimal requirements,
otherwise known under the acronym “POJOs” (Plain Old Java Objects)…they can be seen as a Java EE platform-enhanced version of the JavaBeans component model found on the Java SE platform…It won’t be missed by the reader that Managed Beans have a precursor in the homonymous facility found in the JavaServer Faces (JSF) technology…Managed Beans as defined in this specification represent a generalization of those found in JSF; in particular, Managed Beans can be used anywhere in a Java EE application, not just in web modules. For example, in the basic component model, Managed Beans must provide a no-argument constructor, but a specification that builds on Managed Beans, such as CDI (JSR-299), can relax that requirement and allow Managed Beans to provide constructors with more complex signatures, as long as they follow some well-defined rules...A Managed Bean must not be: a final class, an abstract class, or a non-static inner class. A Managed Bean may not be serializable unlike a regular JavaBean component.”
Thus, the specification for Managed Beans, otherwise known as POJOs or POJO beans, allows extension as in CDI.
CDI Beans
The CDI specification re-defines managed beans as:
When running in Java EE, a top-level Java class is a managed bean if it meets the requirements:
• It is not an inner class.
• It is a non-abstract class, or is annotated #Decorator.
• It does not implement javax.enterprise.inject.spi.Extension.
• It is not annotated #Vetoed or in a package annotated #Vetoed.
• It has an appropriate constructor, either: the class has a constructor with no parameters, or the class declares a constructor annotated #Inject.
All Java classes that meet these conditions are managed beans and thus no special declaration is
required to define a managed bean. Or
if it is defined to be a managed bean by any
other Java EE specification and if
• It is not annotated with an EJB component-defining annotation or declared as an EJB bean class
in ejb-jar.xml.
Bean constructors can have simple-type parameters since simple-types can be injected with the #Inject annotation.
EJBs
EJBs run in an EJB container. The EJB specification says: “A session bean component is a Managed Bean." “The class must have a public constructor that takes no arguments,” it says for both session bean and message-driven bean. Furthermore, it says, “The session bean class is not required to implement the SessionBean interface or the Serializable interface.” For the same reason as JSF beans, that EJB3 dependency injection is basically resource injection, JSF beans do not support constructors with arguments, that is, via dependency injection. However, if the EJB container implements CDI, “ Optionally: The class may have an additional constructor annotated with the Inject annotation, “ it says for both session bean and message-driven bean because, “An EJB packaged into a CDI bean archive and not annotated with javax.enterprise.inject.Vetoed annotation, is considered a CDI-enabled bean.”
As per the Wikipedia:
The class must have a public default constructor (with no arguments). This allows easy instantiation within editing and activation frameworks.
The class properties must be accessible using get, set, is (can be used for boolean properties instead of get), and other methods (so-called accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument.
The class should be serializable. (This allows applications and frameworks to reliably save, store, and restore the bean's state in a manner independent of the VM and of the platform.)
For more information follow this link.
Regarding the second part of your question, serialization is a persistence mechanism used to store objects as a sequence of signed bytes. Put less formally, it stores the state of an object so you can retrieve it later, by deserialization.
A Java Bean is a Java class (conceptual) that should follow the following conventions:
It should have a no-argument constructor.
It should be serializable.
It should provide methods to set and get the values of the properties, known as getter and setter methods.
It is a reusable software component. It can encapsulate many objects into one object so that same object can be accessed from multiples places and is a step towards easy maintenance of code.
They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. The name "Bean" was given to encompass this standard, which aims to create reusable software components for Java. According to Wikipedia.
The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. According to Spring IoC.
It was repeated 6 or 7 times above that there is a no-argument constructor requirement for JavaBeans.
This is WRONG, there is no such requirement, especially in the context of Java Spring.
There is also no mention of that requirement in version (1.01) of the specification that describes the JavaBeanns APIs (https://download.oracle.com/otndocs/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/). Even more - this specification mentions 'null constructor' only 2 times in the following contexts:
"Each customizer should have a null constructor."
"Each PropertyEditor should have a null constructor."
So, it does not seem like the authors of the spec don't know or are not willing to use the term "null constructor", still no mention of it for the JavaBeans proper.
A Java Bean is any Java class that satisfies the following three criteria:
It should implement the serializable interface (a Marker interface).
The constructor should be public and have no arguments (what other people call a "no-arg constructor").
It should have getter and setters.
Good to note the serialVersionUID field is important for maintaining object state.
The below code qualifies as a bean:
public class DataDog implements java.io.Serializable {
private static final long serialVersionUID = -3774654564564563L;
private int id;
private String nameOfDog;
// The constructor should NOT have arguments
public DataDog () {}
/** 4. getter/setter */
// Getter(s)
public int getId() {
return id;
}
public String getNameOfDog() {
return nameOfDog;
}
// Setter(s)
public void setId(int id) {
this.id = id;
}
public void setNameOfDog(String nameOfDog) {
this.nameOfDog = nameOfDog;
}}
If you are familiar with C/Golang, you never heard C bean or Go bean because they have struct keyword, that developers can easily define structure types without writing complicated OOP keywords.
type User struct {
Name string
Age int
}
var user User
user.Name = "name"
user.Age = 18
var bytes, err = json.Marshal(user)
It's Java's mistake that lack of struct types, and developers find this bad shortage.
Then Java Bean is invented as just another boring rule to make class pretending struct, peace your editor or compiler won't be crying or yelling about your unsafe access to class members.
To understand JavaBean you need to notice the following:
JavaBean is conceptual stuff and can not represent a class of specific things
JavaBean is a development tool can be visualized in the operation of reusable software components
JavaBean is based on the Sun JavaBeans specification and can be reusable components. Its biggest feature is the re-usability.
POJO (plain old Java object): POJOs are ordinary Java objects, with no restriction other than those forced by the Java Language.
Serialization: It is used to save state of an object and send it across a network. It converts the state of an object into a byte stream. We can recreate a Java object from the byte stream by process called deserialization.
Make your class implement java.io.Serializable interface. And use writeObject() method of ObjectOutputStream class to achive Serialization.
JavaBean class: It is a special POJO which have some restriction (or convention).
Implement serialization
Have public no-arg constructor
All properties private with public getters & setter methods.
Many frameworks - like Spring - use JavaBean objects.
If you want to understand Java-Beans, you first have to understand software-components.
Software components
A software-component is a part of an application that runs a specific operation. A software component can also be part of a service.
A component is:
Coupled (has dependencies)
Statefull (it saves the states of instance variables)
Not standarised, it is designed for a specific use case (main difference between Java-EE Beans)
Runs in client machine
Java Beans (Enterprise Beans)
Standarised components that run in a Java EE-server
Including different business logics to complete a specific service
Simplify development of complex multilayer distributed systems
Java Beans are more of a concept to manage big systems. Thats why they need standarization.
Source
In practice, Beans are just objects which are handy to use. Serializing them means to be able easily to persist them (store in a form that is easily recovered).
Typical uses of Beans in real world:
simple reusable objects POJO (Plain Old Java Objects)
visual objects
Spring uses Beans for objects to handle (for instance, User object that needs to be serialized in session)
EJB (Enterprise Java Beans), more complex objects, like JSF Beans (JSF is old quite outdated technology) or JSP Beans
So in fact, Beans are just a convention / standard to expect something from a Java object that it would behave (serialization) and give some ways to change it (setters for properties) in a certain way.
How to use them, is just your invention, but most common cases I enlisted above.
A Java Bean is a component or the basic building block in the JavaBeans architecture. The JavaBeans architecture is a component architecture that benefits from reusability and interoperability of a component-based approach.
A valid component architecture should allow programs to be assembled from
software building blocks (Beans in this case), perhaps provided by different vendors and also make it possible for an architect / developer to select a component (Bean), understand its capabilities, and incorporate it into an application.
Since classes/objects are the basic building blocks of an OOP language like Java, they are the natural contenders for being the Bean in the JavaBeans architecture.
The process of converting a plain Java class to a Java bean is actually nothing more than making it a reusable and interoperable component. This would translate into a Java class having abilities like:
controlling the properties, events, and methods of a class that are exposed to another application. (You can have a BeanInfo class that reports only those properties, events and methods that the external application needs.)
persistence (being serialisable or externizable - this would also imply having no-argument constructors, using transient for fields)
ability to register for events and also to generate events (e.g., making use of bound and constraint properties)
customizers (to customise the Bean via GUIs or by providing documentation)
In order for a Java class to be termed a Java bean it is not necessary that they need to possess all the above abilities. Instead, it implies to implement a subset of the above relevant to the context (e.g., a bean in a certain framework may not need customizers, some other bean may not need bound and constrained properties, etc.)
Almost all leading frameworks and libraries in Java adhere to the JavaBeans architecture implicitly, in order to reap the above benefits.
Spring #Bean annotation indicates that a method produces a bean to be managed by the Spring container.
More reference: https://www.concretepage.com/spring-5/spring-bean-annotation
In my project I have a small data structure Key.
public class Key implements Serializable {
private static final long serialVersionUID = 1L;
public String db;
public String ref;
public Object id;
protected Key() {
}
public Key(String db, String ref, Object id) {
this.db = db;
this.ref = ref;
this.id = id;
}
}
Yes this class is simple and every field is publicly accessible.
But someone has suggested I use POJO style classes instead but when I asked why they were unable to tell me.
In my opinion , calling getters and setters is slower than direct access to a field.
So why I must use POJO programming style?
Taken from Wikipedia:
POJO is an acronym for Plain Old Java Object. The name is used to
emphasize that a given object is an ordinary Java Object, not a
special object.
A POJO is usually simple so won't depend on other libraries, interfaces or annotations. This increases the chance that this can be reused in multiple project types (web, desktop, console etc).
As someone has already pointed out in the comments, your object is technically a POJO already however you have specifically asked about getters and setters which are more akin to JavaBeans.
There are a number of reasons I can think of for using getters and setters:
You might only want to get some of the values (I.E. read only values). With fields, clients can both get and set the values directly. Fields can be made read-only if they are marked as final although this doesn't always guarantee that they are immutable (see point 9).
Getter & setter methods allow you to change the underlying data type without breaking the public interface of your class which makes it (and your application) more robust and resilient to changes.
You might want to call some other code such as raising a notification when the value is obtained or changed. This is not possible with your current class.
You are exposing the implementation of your class which could be a security risk in some cases.
Java beans are designed around POJO's which means that if your class is not implemented as one it can't be used by certain tools and libraries that expect your class to adhere to these well established principles.
You can expose values that are not backed by a field I.E. calculated values such as getFullName() which is a concatenation of getFirstName() and getLastName() which are backed by fields.
You can add validation to your setter methods to ensure that the values being passed are correct. This ensures that your class is always in a valid state.
You can set a breakpoint in your getters and setters so that you can debug your code when the values are obtained or changed.
If the field is an object (I.E. not a primitive type) then the internal state of your class can be modified by other objects which can lead to bugs or security risks. You can protect against this scenario in your POJO's getter by returning a copy of the object so that clients can work with the data without affecting the state of your object. Note that having a final field does not always protect you against this sort of attack as clients can still make changes to the object being referenced (providing that object is itself mutable) you just cannot point the field at a different reference once it has been set.
Yes, accessing or setting the values via method calls may be slower than direct field access but the difference is barely noticeable and it certainly won't be the bottleneck in your program.
Whilst the advantages are clear this does not mean that getters and setters are a silver bullet. There are a number of 'gotchas' to consider when designing real world, robust scalable classes.
This answer to a very similar question looks at some considerations in detail when designing a class that has getters and setters. Although the suggestions may be more relevant depending on the type of class you are designing E.G. a class that forms part of an API in a large system as opposed to a simple data transfer object.
Also note that there may be certain scenarios where a class with direct field may be advantageous such as when speed is essential or memory is limited although this should only be considered after profiling your code and finding that it is actually a bottleneck.
Also be careful that you are not just wrapping all of your fields in getters and setters as this is really missing the point of encapsulation.
This answer provides a good summary of the reasons for choosing a POJO over a JavaBean style object with getters and setters.
Use private class variables and public getters and setters which will provide you Encapsulation.
Getters and setters, especially the simplest forms will just be inlined by the JIT compiler and thus remove the method call overhead. This sounds very much like premature optimisation. If you ever get a bottleneck, then profile and look where it occurs. I am fairly certain it'll be not in property accesses.
Get yourself the book Effective Java.
Item 14, in public classes use accessor methods not public fields.
In this Joshua Bloch says there is nothing inheriently wrong with public fields in package-private or nested classes but strongly advises against use public classes.
He goes into much more detail on the subject, it's a great book, suggest you get a copy.
Imagine if some other programmer is using your code. If you don't provide setter and getter methods then he can directly call your variable and it surely will affect to your code. And it may lead to security issues
So by providing POJO class you are forcing him to call on your methods rather than directly calling your Instance variables.
What is the "correct" way to access an object's properties from within an object method that is not a getter/setter method?
Getter/Setter is the recommended way of accessing properties of an object. Otherwise you to have to use public properties, but public properties are not recommended.
If a classes' properties don't have getters and they are not visible (e.g. not public), that means that the class is designed so that you can't access them. In that case, there is no proper way to access them.
Flipping this around, if you are designing a class and you intend that other classes can access its attributes, you ought to provide getters. You could alternatively declare the attributes to be public, protected or package private, but that makes your abstraction leaky and has a number of undesirable consequences.
If you are asking how one of an object's methods should access its own attributes, the simple answer is whichever way is most convenient. If the class has getters, you could call them. Alternatively, you could just access the attributes directly. The problems of leaky abstraction don't apply in this case because the method accessing the state is inside the abstraction boundary.
This is mostly a matter of preference.
I personally prefer not to use the getters and setters in my object. This increases readability, allows me to change my getters and settings to return copies (of lists mostly) without it changing my own object. If you do something special in your getter then you can make a helper method that is used by both your getter and your other functions. This will go wrong if your classes get too large though (so don't make large classes). I don't like how using a getter setter hides the side effects inside the object (unlike for external users, they should be hidden from any side effects inside the object), when you want to have the side effects, give the private method a clear name indiciting it has them.
First off I'll answer the question as is:
What is the "correct" way to access an object's properties from within an object method that is not a getter/setter method?
When you are within an object, you can reference the properties directly where the method is part of the object. For example:
public class testClass() {
public int x;
private someMethod() {
x = 4;
}
}
To answer the comment:
I think the question can be reformulated: Should I use getters and setters when implementing my object methods? Or should I access member variables directly?
You should always hide the internal data and other implementation details within a class as much as possible; seperating the API from the implementation (a.k.a encapsulation). Encapsulation decouples the modules thereby allowing them to be developed, tested and modified in isolation.
Generally, you should use the lowest access modifier possible (e.g. private, protected, package-private) whilst maintaining functionality for the application you're writing. The benefits of designing and devloping this way is that you can change implementation details without breaking code that uses the modules. If you make everything public, and other people are using your classes, you are forced to support it forever maintaining compatibility - or until they change their implementation that is using your modules.
Instance fields should never be public as you give up the ability to limit the values that can be stored in the field, and if it is a mutable object, you open your object up for misuse (see here). It is important to note too that classes with public mutable fields are not thread-safe. It is also important to note that instance fields that are declared public static final but are mutable objects can also be modified and can be a security risk.
Basically, in public classes - always use accessor methods, not public fields. It allows you to protect your mutable objects from modification outside of the class (be it intentionally or unintentionally) and allows you to change implementation detail later without harming your clients.
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 JavaBean and a regular class?
Is there any special definition or an Interface?
Basically, why is there a term for this?
Also what does the Serializable interface mean?
A JavaBean is just a standard. It is a regular Java class, except it follows certain conventions:
All properties are private (use getters/setters)
A public no-argument constructor
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 is 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 to stream any object you pass into it, it knows it can because your object is serializable (assuming the library requires your objects be proper JavaBeans).
There's a term for it to make it sound special. The reality is nowhere near so mysterious.
Basically, a "Bean":
is a serializable object (that is, it implements java.io.Serializable, and does so correctly), that
has "properties" whose getters and setters are just methods with certain names (like, say, getFoo() is the getter for the "Foo" property), and
has a public zero-argument constructor (so it can be created at will and configured by setting its properties).
As for Serializable: That is nothing but a "marker interface" (an interface that doesn't declare any functions) that tells Java that the implementing class consents to (and implies that it is capable of) "serialization" -- a process that converts an instance into a stream of bytes. Those bytes can be stored in files, sent over a network connection, etc., and have enough information to allow a JVM (at least, one that knows about the object's type) to reconstruct the object later -- possibly in a different instance of the application, or even on a whole other machine!
Of course, in order to do that, the class has to abide by certain limitations. Chief among them is that all instance fields must be either primitive types (int, bool, etc.), instances of some class that is also serializable, or marked as transient so that Java won't try to include them. (This of course means that transient fields will not survive the trip over a stream. A class that has transient fields should be prepared to reinitialize them if necessary.)
A class that can not abide by those limitations should not implement Serializable (and, IIRC, the Java compiler won't even let it do so.)
JavaBeans are Java classes which adhere to an extremely simple coding convention.
All you have to do is to
implement the java.io.Serializable interface - to save the state of an
object
use a public empty argument constructor - to instantiate the object
provide public getter/setter methods - to get and set the values of private variables (properties).
Properties of JavaBeans
A JavaBean is a Java object that satisfies certain programming conventions:
The JavaBean class must implement either Serializable or
Externalizable
The JavaBean class must have a no-arg constructor
All JavaBean properties must have public setter and getter methods
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;
}
}
Explanation with an example.
1. import java.io.Serializable
As for the Serialization, see the documentation.
2. private fields
Fields should be private for prevent outer classes to easily modify those fields.
Instead of directly accesing to those fields, usuagly getter/setter methods are used.
3. Constructor
A public constructor without any argument.
4. getter/setter
Getter and setter methods for accessing and modifying private fields.
/** 1. import java.io.Serializable */
public class User implements java.io.Serializable {
/** 2. private fields */
private int id;
private String name;
/** 3. Constructor */
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
/** 4. getter/setter */
// getter
public int getId() {
return id;
}
public String getName() {
return name;
}
// setter
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
Java Beans are used for a less code and more work approach...
Java Beans are used throughout Java EE as a universal contract for runtime discovery and access. For example, JavaServer Pages (JSP) uses Java Beans as data transfer objects between pages or between servlets and JSPs. Java EE's JavaBeans Activation Framework uses Java Beans for integrating support for MIME data types into Java EE. The Java EE Management API uses JavaBeans as the foundation for the instrumentation of resources to be managed in a Java EE environment.
About Serialization:
In object serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
You will find serialization useful when deploying your project across multiple servers since beans will be persisted and transferred across them.
Just a little background/update on the bean concept. Many other answers actually have the what but not so much why of them.
They were invented early on in Java as part of building GUIs. They followed patterns that were easy for tools to pull apart letting them create a properties panel so you could edit the attributes of the Bean. In general, the Bean properties represented a control on the screen (Think x,y,width,height,text,..)
You can also think of it as a strongly typed data structure.
Over time these became useful for lots of tools that used the same type of access (For example, Hibernate to persist data structures to the database)
As the tools evolved, they moved more towards annotations and away from pulling apart the setter/getter names. Now most systems don't require beans, they can take any plain old Java object with annotated properties to tell them how to manipulate them.
Now I see beans as annotated property balls--they are really only useful for the annotations they carry.
Beans themselves are not a healthy pattern. They destroy encapsulation by their nature since they expose all their properties to external manipulation and as they are used there is a tendency (by no means a requirement) to create code to manipulate the bean externally instead of creating code inside the bean (violates "don't ask an object for its values, ask an object to do something for you"). Using annotated POJOs with minimal getters and no setters is much more OO restoring encapsulation and with the possibility of immutability.
By the way, as all this stuff was happening someone extended the concept to something called Enterprise Java Beans. These are... different. and they are complicated enough that many people felt they didn't understand the entire Bean concept and stopped using the term. This is, I think, why you generally hear beans referred to as POJOs (since every Java object is a POJO this is technically OK, but when you hear someone say POJO they are most often thinking about something that follows the bean pattern)
JavaBeans is a standard, and its basic syntax requirements have been clearly explained by the other answers.
However, IMO, it is more than a simple syntax standard. The real meaning or intended usage of JavaBeans is, together with various tool supports around the standard, to facilitate code reuse and component-based software engineering, i.e. enable developers to build applications by assembling existing components (classes) and without having to write any code (or only have to write a little glue code). Unfortunately this technology is way under-estimated and under-utilized by the industry, which can be told from the answers in this thread.
If you read Oracle's tutorial on JavaBeans, you can get a better understanding in that.
For a Java class to be usable as a Java bean, its method names need to be as per the JavaBeans guidelines (also called design patterns) for properties, methods, and events. The class needs to be a public class to be accessible to any beanbox tool or container. The container must be able to instantiate it; with the class as public, the container should be able to do so even if no explicit, public, zero-args constructor is provided. (A Java public class with no explicit constructor has a default public zero-args constructor.) So, minimally, a Java public class, even with a property as the sole member (of course, accompanying public getter and setter required) or a public method as the sole member, is a Java bean. The property can either be a read-only property (it has a getter method but no setter) or write-only property (has a setter method only). A Java public class with a public event listener registration method as the sole member is also a Java bean. The JavaBeans specification doesn’t require that if such a Java class has an explicit public constructor, it should be a zero-args one. If one could provide a file (with an extension, say, .ser) containing a serialized instance, a beanbox tool may be able to use that file to instantiate a prototype bean. Otherwise, the class would need a constructor, either explicit or default, that is public as well as zero-args.
Once the bean is instantiated, the JavaBeans API ( java.beans.*) can introspect it and call methods on it. If no class implementing the interface BeanInfo or extending a BeanInfo implementation,such as the SimpleBeanInfo class, is available, the introspection involves using reflection (implicit introspection) to study the methods supported by a target bean and then applying simple design patterns(the guidelines) to deduce from those methods what properties, events, and public methods are supported. If a class implementing the interface BeanInfo (for a bean Foo, it must be named FooBeanInfo) is available, the API bypasses implicit introspection and uses public methods (getPropertyDescriptor(), getMethodDescriptors(), getEventSetDescriptors() ) of this class to get the information. If a class extending SimpleBeanInfo is available, depending on which of the SimpleBeanInfo public methods (getPropertyDescriptor(), getMethodDescriptors(), getEventSetDescriptors() ) are overridden, it will use those overridden methods(s) to get information; for a method that is not overridden, it’ll default to the corresponding implicit introspection. A bean needs to be instantiated anyway, even if no implicit introspection is carried out on it. Thus, the requirement of a public zero-args constructor. But, of course, the Serializable or Externalizable interface isn’t necessary for it to be recognized. However, the JavaBeans specification says, ‘We’d also like it to be “trivial” for the common case of a tiny Bean that simply wants to have its internal state saved and doesn’t want to think about it.’ So, all beans must implement Serializable or Externalizable interface.
Overall, the JavaBeans specification isn’t hard and fast about what constitutes a bean. "Writing JavaBeans components is surprisingly easy. You don't need a special tool and you don't have to implement any interfaces. Writing beans is simply a matter of following certain coding conventions. All you have to do is make your class look like a bean — tools that use beans will be able to recognize and use your bean." Trivially, even the following class is a Java bean,
public class Trivial implements java.io.Serializable {}
The description so far is the Java SE version (JavaBeans). The beans, as described below, are the Java EE versions. These versions have been built on the underlying ideas as explained above. In particular, one main idea they consider is what if a bean constructor does have some parameters. These parameters could be either simple types, class/interface types or both. There should be a way to let the container know values that it can substitute for the parameters when instantiating the bean. The way to do so is that the programmer can configure (specify values) by say annotations or XML configuration files or a mix of both.
Spring Beans
Spring beans run in a Spring IoC container. The programmer can configure via XML configuration files, annotations or a mix of both.
In Spring, if a bean constructor has simple-type or class/interface type parameters, values can be assigned as strings (as the <value> attribute of a constructor argument element in the former case and as an <idref> element of a constructor argument in the latter case) in a type-safe manner. Making references to other Spring beans (called collaborators; via the <ref> element in a constructor argument element) is basically dependency injection and is also typesafe. Obviously, a dependency (collaborator bean) might have a constructor with injected parameters; those injected dependency(ies) might have a constructor with parameters and so on. This scenario should ultimately terminate at injected dependency(ies) that are prototype beans that the container can instantiate by constructing.
JSF Managed Beans
JSF managed beans run in a web container. They can be configured either with the #ManagedBean annotation or with an application configuration resource file managed-bean.xml. The JSF spec supports injection via resource injection (not typesafe) only. This injection is not fit for injection on constructors. In any case, the spec requires that a JSF managed bean must have a public zero-argument constructor. Further it says, “As of version 2.3 of this specification, use of the managed bean facility as specified in this section is strongly
discouraged. A better and more cohesively integrated solution for solving the same problem is to use Contexts and Dependency Injection (CDI), as specified in JSR-365." In other words, CDI managed beans should be used, which do offer typesafe dependency injection on constructors akin to Spring beans. The CDI specification adopts the Managed Beans specification, which applies to all containers of the JEE platform, not just the web tier. Thus, the web container needs to implement the CDI specification.
Managed Beans
Here is an extract from the Managed Bean specification
“ Managed Beans are container-managed objects with minimal requirements,
otherwise known under the acronym “POJOs” (Plain Old Java Objects)…they can be seen as a Java EE platform-enhanced version of the JavaBeans component model found on the Java SE platform…It won’t be missed by the reader that Managed Beans have a precursor in the homonymous facility found in the JavaServer Faces (JSF) technology…Managed Beans as defined in this specification represent a generalization of those found in JSF; in particular, Managed Beans can be used anywhere in a Java EE application, not just in web modules. For example, in the basic component model, Managed Beans must provide a no-argument constructor, but a specification that builds on Managed Beans, such as CDI (JSR-299), can relax that requirement and allow Managed Beans to provide constructors with more complex signatures, as long as they follow some well-defined rules...A Managed Bean must not be: a final class, an abstract class, or a non-static inner class. A Managed Bean may not be serializable unlike a regular JavaBean component.”
Thus, the specification for Managed Beans, otherwise known as POJOs or POJO beans, allows extension as in CDI.
CDI Beans
The CDI specification re-defines managed beans as:
When running in Java EE, a top-level Java class is a managed bean if it meets the requirements:
• It is not an inner class.
• It is a non-abstract class, or is annotated #Decorator.
• It does not implement javax.enterprise.inject.spi.Extension.
• It is not annotated #Vetoed or in a package annotated #Vetoed.
• It has an appropriate constructor, either: the class has a constructor with no parameters, or the class declares a constructor annotated #Inject.
All Java classes that meet these conditions are managed beans and thus no special declaration is
required to define a managed bean. Or
if it is defined to be a managed bean by any
other Java EE specification and if
• It is not annotated with an EJB component-defining annotation or declared as an EJB bean class
in ejb-jar.xml.
Bean constructors can have simple-type parameters since simple-types can be injected with the #Inject annotation.
EJBs
EJBs run in an EJB container. The EJB specification says: “A session bean component is a Managed Bean." “The class must have a public constructor that takes no arguments,” it says for both session bean and message-driven bean. Furthermore, it says, “The session bean class is not required to implement the SessionBean interface or the Serializable interface.” For the same reason as JSF beans, that EJB3 dependency injection is basically resource injection, JSF beans do not support constructors with arguments, that is, via dependency injection. However, if the EJB container implements CDI, “ Optionally: The class may have an additional constructor annotated with the Inject annotation, “ it says for both session bean and message-driven bean because, “An EJB packaged into a CDI bean archive and not annotated with javax.enterprise.inject.Vetoed annotation, is considered a CDI-enabled bean.”
As per the Wikipedia:
The class must have a public default constructor (with no arguments). This allows easy instantiation within editing and activation frameworks.
The class properties must be accessible using get, set, is (can be used for boolean properties instead of get), and other methods (so-called accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument.
The class should be serializable. (This allows applications and frameworks to reliably save, store, and restore the bean's state in a manner independent of the VM and of the platform.)
For more information follow this link.
Regarding the second part of your question, serialization is a persistence mechanism used to store objects as a sequence of signed bytes. Put less formally, it stores the state of an object so you can retrieve it later, by deserialization.
A Java Bean is a Java class (conceptual) that should follow the following conventions:
It should have a no-argument constructor.
It should be serializable.
It should provide methods to set and get the values of the properties, known as getter and setter methods.
It is a reusable software component. It can encapsulate many objects into one object so that same object can be accessed from multiples places and is a step towards easy maintenance of code.
They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. The name "Bean" was given to encompass this standard, which aims to create reusable software components for Java. According to Wikipedia.
The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. According to Spring IoC.
It was repeated 6 or 7 times above that there is a no-argument constructor requirement for JavaBeans.
This is WRONG, there is no such requirement, especially in the context of Java Spring.
There is also no mention of that requirement in version (1.01) of the specification that describes the JavaBeanns APIs (https://download.oracle.com/otndocs/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/). Even more - this specification mentions 'null constructor' only 2 times in the following contexts:
"Each customizer should have a null constructor."
"Each PropertyEditor should have a null constructor."
So, it does not seem like the authors of the spec don't know or are not willing to use the term "null constructor", still no mention of it for the JavaBeans proper.
A Java Bean is any Java class that satisfies the following three criteria:
It should implement the serializable interface (a Marker interface).
The constructor should be public and have no arguments (what other people call a "no-arg constructor").
It should have getter and setters.
Good to note the serialVersionUID field is important for maintaining object state.
The below code qualifies as a bean:
public class DataDog implements java.io.Serializable {
private static final long serialVersionUID = -3774654564564563L;
private int id;
private String nameOfDog;
// The constructor should NOT have arguments
public DataDog () {}
/** 4. getter/setter */
// Getter(s)
public int getId() {
return id;
}
public String getNameOfDog() {
return nameOfDog;
}
// Setter(s)
public void setId(int id) {
this.id = id;
}
public void setNameOfDog(String nameOfDog) {
this.nameOfDog = nameOfDog;
}}
If you are familiar with C/Golang, you never heard C bean or Go bean because they have struct keyword, that developers can easily define structure types without writing complicated OOP keywords.
type User struct {
Name string
Age int
}
var user User
user.Name = "name"
user.Age = 18
var bytes, err = json.Marshal(user)
It's Java's mistake that lack of struct types, and developers find this bad shortage.
Then Java Bean is invented as just another boring rule to make class pretending struct, peace your editor or compiler won't be crying or yelling about your unsafe access to class members.
To understand JavaBean you need to notice the following:
JavaBean is conceptual stuff and can not represent a class of specific things
JavaBean is a development tool can be visualized in the operation of reusable software components
JavaBean is based on the Sun JavaBeans specification and can be reusable components. Its biggest feature is the re-usability.
POJO (plain old Java object): POJOs are ordinary Java objects, with no restriction other than those forced by the Java Language.
Serialization: It is used to save state of an object and send it across a network. It converts the state of an object into a byte stream. We can recreate a Java object from the byte stream by process called deserialization.
Make your class implement java.io.Serializable interface. And use writeObject() method of ObjectOutputStream class to achive Serialization.
JavaBean class: It is a special POJO which have some restriction (or convention).
Implement serialization
Have public no-arg constructor
All properties private with public getters & setter methods.
Many frameworks - like Spring - use JavaBean objects.
If you want to understand Java-Beans, you first have to understand software-components.
Software components
A software-component is a part of an application that runs a specific operation. A software component can also be part of a service.
A component is:
Coupled (has dependencies)
Statefull (it saves the states of instance variables)
Not standarised, it is designed for a specific use case (main difference between Java-EE Beans)
Runs in client machine
Java Beans (Enterprise Beans)
Standarised components that run in a Java EE-server
Including different business logics to complete a specific service
Simplify development of complex multilayer distributed systems
Java Beans are more of a concept to manage big systems. Thats why they need standarization.
Source
In practice, Beans are just objects which are handy to use. Serializing them means to be able easily to persist them (store in a form that is easily recovered).
Typical uses of Beans in real world:
simple reusable objects POJO (Plain Old Java Objects)
visual objects
Spring uses Beans for objects to handle (for instance, User object that needs to be serialized in session)
EJB (Enterprise Java Beans), more complex objects, like JSF Beans (JSF is old quite outdated technology) or JSP Beans
So in fact, Beans are just a convention / standard to expect something from a Java object that it would behave (serialization) and give some ways to change it (setters for properties) in a certain way.
How to use them, is just your invention, but most common cases I enlisted above.
A Java Bean is a component or the basic building block in the JavaBeans architecture. The JavaBeans architecture is a component architecture that benefits from reusability and interoperability of a component-based approach.
A valid component architecture should allow programs to be assembled from
software building blocks (Beans in this case), perhaps provided by different vendors and also make it possible for an architect / developer to select a component (Bean), understand its capabilities, and incorporate it into an application.
Since classes/objects are the basic building blocks of an OOP language like Java, they are the natural contenders for being the Bean in the JavaBeans architecture.
The process of converting a plain Java class to a Java bean is actually nothing more than making it a reusable and interoperable component. This would translate into a Java class having abilities like:
controlling the properties, events, and methods of a class that are exposed to another application. (You can have a BeanInfo class that reports only those properties, events and methods that the external application needs.)
persistence (being serialisable or externizable - this would also imply having no-argument constructors, using transient for fields)
ability to register for events and also to generate events (e.g., making use of bound and constraint properties)
customizers (to customise the Bean via GUIs or by providing documentation)
In order for a Java class to be termed a Java bean it is not necessary that they need to possess all the above abilities. Instead, it implies to implement a subset of the above relevant to the context (e.g., a bean in a certain framework may not need customizers, some other bean may not need bound and constrained properties, etc.)
Almost all leading frameworks and libraries in Java adhere to the JavaBeans architecture implicitly, in order to reap the above benefits.
Spring #Bean annotation indicates that a method produces a bean to be managed by the Spring container.
More reference: https://www.concretepage.com/spring-5/spring-bean-annotation
I'm not sure about the difference. I'm using Hibernate and, in some books, they use JavaBean and POJO as an interchangeable term. I want to know if there is a difference, not just in the Hibernate context, but as general concepts.
A JavaBean follows certain conventions. Getter/setter naming, having a public default constructor, being serialisable etc. See JavaBeans Conventions for more details.
A POJO (plain-old-Java-object) isn't rigorously defined. It's a Java object that doesn't have a requirement to implement a particular interface or derive from a particular base class, or make use of particular annotations in order to be compatible with a given framework, and can be any arbitrary (often relatively simple) Java object.
All JavaBeans are POJOs but not all POJOs are JavaBeans.
A JavaBean is a Java object that satisfies certain programming conventions:
the JavaBean class must implement either Serializable or Externalizable;
the JavaBean class must have a public no-arg constructor;
all JavaBean properties must have public setter and getter methods (as appropriate);
all JavaBean instance variables should be private.
According to Martin Fowler a POJO is an object which encapsulates Business Logic while a Bean (except for the definition already stated in other answers) is little more than a container for holding data and the operations available on the object merely set and get data.
The term was coined while Rebecca Parsons, Josh MacKenzie and I were
preparing for a talk at a conference in September 2000. In the talk we
were pointing out the many benefits of encoding business logic into
regular java objects rather than using Entity Beans. We wondered why
people were so against using regular objects in their systems and
concluded that it was because simple objects lacked a fancy name. So
we gave them one, and it's caught on very nicely.
http://www.martinfowler.com/bliki/POJO.html
Pojo - Plain old java object
pojo class is an ordinary class without any specialties,class totally loosely coupled from technology/framework.the class does not implements from technology/framework and does not extends from technology/framework api that class is called pojo class.
pojo class can implements interfaces and extend classes but the super class or interface should not be an technology/framework.
Examples :
1.
class ABC{
----
}
ABC class not implementing or extending from technology/framework that's why this is pojo class.
2.
class ABC extends HttpServlet{
---
}
ABC class extending from servlet technology api that's why this is not a pojo class.
3.
class ABC implements java.rmi.Remote{
----
}
ABC class implements from rmi api that's why this is not a pojo class.
4.
class ABC implements java.io.Serializable{
---
}
this interface is part of java language not a part of technology/framework.so this is pojo class.
5.
class ABC extends Thread{
--
}
here thread is also class of java language so this is also a pojo class.
6.
class ABC extends Test{
--
}
if Test class extends or implements from technologies/framework then ABC is also not a pojo class because it inherits the properties of Test class.
if Test class is not a pojo class then ABC class also not a pojo class.
7.
now this point is an exceptional case
#Entity
class ABC{
--
}
#Entity is an annotation given by hibernate api or jpa api but still we can call this class as pojo class.
class with annotations given from technology/framework is called pojo class by this exceptional case.
POJO: If the class can be executed with underlying JDK,without any other external third party libraries support then its called POJO
JavaBean: If class only contains attributes with accessors(setters and getters) those are called javabeans.Java beans generally will not contain any bussiness logic rather those are used for holding some data in it.
All Javabeans are POJOs but all POJO are not Javabeans
Java beans are special type of POJOs.
Specialities listed below with reason
In summary: similarities and differences are:
java beans: Pojo:
-must extends serializable -no need to extends or implement.
or externalizable.
-must have public class . - must have public class
-must have private instance variables. -can have any access specifier variables.
-must have public setter and getter method. - may or may not have setter or getter method.
-must have no-arg constructor. - can have constructor with agruments.
All JAVA Beans are POJO but not all POJOs are JAVA Beans.
POJOS with certain conventions (getter/setter,public no-arg constructor ,private variables) and are in action(ex. being used for reading data by form) are JAVABEANS.
You've seen the formal definitions above, for all they are worth.
But don't get too hung up on definitions.
Let's just look more at the sense of things here.
JavaBeans are used in Enterprise Java applications, where users frequently access data and/or application code remotely, i.e. from a server (via web or private network) via a network. The data involved must therefore be streamed in serial format into or out of the users' computers - hence the need for Java EE objects to implement the interface Serializable. This much of a JavaBean's nature is no different to Java SE application objects whose data is read in from, or written out to, a file system.
Using Java classes reliably over a network from a range of user machine/OS combinations also demands the adoption of conventions for their handling. Hence the requirement for implementing these classes as public, with private attributes, a no-argument constructor and standardised getters and setters.
Java EE applications will also use classes other than those that were implemented as JavaBeans. These could be used in processing input data or organizing output data but will not be used for objects transferred over a network. Hence the above considerations need not be applied to them bar that the be valid as Java objects. These latter classes are referred to as POJOs - Plain Old Java Objects.
All in all, you could see Java Beans as just Java objects adapted for use over a network.
There's an awful lot of hype - and no small amount of humbug - in the software world since 1995.
All Pojo(s) are JavaBean(s), but not the opposite.
What is POJO?
A POJO has no naming convention for properties or methods. We don't follow any real convention for constructing, accessing, modifying the class's state.
Example:
public class Pojo {
public String firstname;
public String LASTName;
public String name() {
return this.firstname + " " + this.LASTName;
}
}
here, I could have replaced firstname by first_name or Firstname or by any noun and the same with the variable LASTName.
The term has most likely gained widespread acceptance because of the
need for a common and easily understood term that contrasts with
complicated object frameworks.[2]
Reflection using POJO.
it may limit a framework's ability to favor convention over configuration, understand how to use the class, and augment its functionality.[1]
List<String> propertyNames =
Arrays.stream(PropertyUtils.getPropertyDescriptors(Pojo.class))
.map(PropertyDescriptor::getDisplayName)
.collect(Collectors.toList());
System.out.println(propertyNames);
If we use Third Party Libraries PropertyUtils for reflection we may face issues, as this will result in
[]
What is Java Beans?
A JavaBean is still a POJO but introduces a strict set of rules around
how we implement it:
Access levels – our properties are private and we expose getters and setters.
Method names – our getters and setters follow the getX and
setX convention (in the case of a boolean, isX can be used for a
getter)
Default Constructor – a no-argument constructor must be
present so an instance can be created without providing arguments, for
example during deserialization
Serializable – implementing the Serializable interface allows us to store the state.
Example:
#Getter
#Setter
class Pojo implements Serializable {
public String firstName;
public String lastName;
}
Reflection using Java Bean.
If we again use third party Libraries such as `PropertyUtils` for reflection the result will be different
[firstName,lastName]