Java POJO Class

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn about Plain Old Java Objects, commonly known as POJOs, and their conventions. You will also learn about Java Bean classes. At the end of this lab, you will be able to:


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/method_overloading("`Method Overloading`") java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/serialization("`Serialization`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_attributes("`Class Attributes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/constructors("`Constructors`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/encapsulation("`Encapsulation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("`Exceptions`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/FileandIOManagementGroup -.-> java/files("`Files`") java/FileandIOManagementGroup -.-> java/create_write_files("`Create/Write Files`") java/FileandIOManagementGroup -.-> java/read_files("`Read Files`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/method_overloading -.-> lab-117946{{"`Java POJO Class`"}} java/scope -.-> lab-117946{{"`Java POJO Class`"}} java/serialization -.-> lab-117946{{"`Java POJO Class`"}} java/classes_objects -.-> lab-117946{{"`Java POJO Class`"}} java/class_attributes -.-> lab-117946{{"`Java POJO Class`"}} java/class_methods -.-> lab-117946{{"`Java POJO Class`"}} java/constructors -.-> lab-117946{{"`Java POJO Class`"}} java/encapsulation -.-> lab-117946{{"`Java POJO Class`"}} java/exceptions -.-> lab-117946{{"`Java POJO Class`"}} java/modifiers -.-> lab-117946{{"`Java POJO Class`"}} java/oop -.-> lab-117946{{"`Java POJO Class`"}} java/packages_api -.-> lab-117946{{"`Java POJO Class`"}} java/files -.-> lab-117946{{"`Java POJO Class`"}} java/create_write_files -.-> lab-117946{{"`Java POJO Class`"}} java/read_files -.-> lab-117946{{"`Java POJO Class`"}} java/identifier -.-> lab-117946{{"`Java POJO Class`"}} java/arrays -.-> lab-117946{{"`Java POJO Class`"}} java/comments -.-> lab-117946{{"`Java POJO Class`"}} java/data_types -.-> lab-117946{{"`Java POJO Class`"}} java/operators -.-> lab-117946{{"`Java POJO Class`"}} java/output -.-> lab-117946{{"`Java POJO Class`"}} java/strings -.-> lab-117946{{"`Java POJO Class`"}} java/system_methods -.-> lab-117946{{"`Java POJO Class`"}} end

Create a POJO Class

In this step, we will create a POJO class named Sample. A POJO class can be created in any way and does not need to follow any conventions.

// Sample POJO class
public class Sample{
    public String field1;
    private int field2;
    double field3;

    Sample(String s, int i, double d){
        this.field1 = s;
        this.field2 = i;
        this.field3 = d;
    }

    public String getField1(){
        return field1;
    }

    public double getField3(){
        return field3;
    }
}

Save the file and compile it in the terminal using the following commands:

cd ~/project
javac Sample.java

Understand POJO Class

In this step, we will run the Sample class and see how it works.

public class Main{
    public static void main(String[] args) {
        Sample sample = new Sample("field 1", 100, 123.45);

        System.out.println("Field 1: " + sample.field1);
        System.out.println("Field 2: " + sample.field2);
        System.out.println("Field 3: " + sample.field3);
    }
}

Save the file and run it in the terminal using the following commands:

java Main

Understand Reflection API

In this step, we will use Reflection API to view the properties of the Sample class. Reflection API is a powerful tool that allows you to inspect and modify the behavior of an application.

import org.apache.commons.beanutils.BeanUtils;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        Sample s = new Sample("f1", 0, 0.0);
        try {
            Map<String, Object> properties = BeanUtils.describe(s);
            for (Map.Entry<String, Object> e : properties.entrySet())
                System.out.println(e.getKey() + "->" + e.getValue());
        } catch (Exception e) {
            System.out.print(e);
        }
    }
}

Save the file and compile it in the terminal using the following command:

cd ~/project
javac -cp .:commons-beanutils-1.9.4.jar Main.java

-cp flag is used here to specify the classpath. :commons-beanutils-1.9.4.jar is the path of commons-beanutils package. To run the compiled file, use the following command:

java -cp .:commons-beanutils-1.9.4.jar Main

Create a Java Bean Class

In this step, we will convert the Sample POJO class to a Java Bean class. A Java Bean class is a POJO that follows some conventions and rules.

import java.io.Serializable;

public class Sample implements Serializable{
    private String field1;
    private int field2;
    private double field3;

    public Sample(){}

    public Sample(String s, int i, double d){
        this.field1 = s;
        this.field2 = i;
        this.field3 = d;
    }

    public String getField1(){
        return field1;
    }

    public void setField1(String field1){
        this.field1 = field1;
    }

    public int getField2(){
        return field2;
    }

    public void setField2(int field2){
        this.field2 = field2;
    }

    public double getField3(){
        return field3;
    }

    public void setField3(double field3){
        this.field3 = field3;
    }
}

Understand Java Bean Class

In this step, we will run the Sample class and see how it works.

public class Main{
    public static void main(String[] args) {
        Sample sample = new Sample();
        sample.setField1("field 1");
        sample.setField2(100);
        sample.setField3(123.45);

        System.out.println("Field 1: " + sample.getField1());
        System.out.println("Field 2: " + sample.getField2());
        System.out.println("Field 3: " + sample.getField3());
    }
}

Save the file and compile it in the terminal using the following commands:

cd ~/project
javac Main.java

Understand Reflection API

In this step, we will again use Reflection API to view the properties of the Sample class.

public class Main {
    public static void main(String[] args) throws Exception {
        Sample s = new Sample("f1", 0, 0.0);
        try {
            Map<String, Object> properties = BeanUtils.describe(s);
            for (Map.Entry<String, Object> e : properties.entrySet())
                System.out.println(e.getKey() + "->" + e.getValue());
        } catch (Exception e) {
            System.out.print(e);
        }
    }
}

Save the file and compile it in the terminal using the following commands:

cd ~/project
javac -cp .:commons-beanutils-1.9.4.jar Main.java

-cp flag is used here to specify the classpath. :commons-beanutils-1.9.4.jar is the path of commons-beanutils package. To run the compiled file, use the following command:

java -cp .:commons-beanutils-1.9.4.jar Main

Understand Java Bean Class Serialization

In this step, we will use serialization to store an object of the Sample class in a file. Serialization is used to convert an object into a stream of bytes, which can be saved to disk or sent over a network.

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class Main {
    public static void main(String[] args) throws Exception {
        Sample s = new Sample("f1", 0, 0.0);
        try {
            FileOutputStream fos = new FileOutputStream("sample.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(s);
            oos.close();
            fos.close();
            System.out.println("Object has been serialized");
        } catch (Exception e) {
            System.out.print(e);
        }
    }
}

Save the file and compile it in the terminal using the following commands:

cd ~/project
javac Main.java

Run the compiled file using the following command:

java Main

Understand Java Bean Class Deserialization

In this step, we will use deserialization to read an object of the Sample class from a file. Deserialization is used to convert a stream of bytes back into an object.

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class Main {
    public static void main(String[] args) throws Exception {
        try {
            FileInputStream fis = new FileInputStream("sample.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            Sample s = (Sample) ois.readObject();
            ois.close();
            fis.close();
            System.out.println("Object has been deserialized");
            System.out.println("Field 1: " + s.getField1());
            System.out.println("Field 2: " + s.getField2());
            System.out.println("Field 3: " + s.getField3());
        } catch (Exception e) {
            System.out.print(e);
        }
    }
}

Save the file and compile it in the terminal using the following commands:

cd ~/project
javac Main.java

Run the compiled file using the following command:

java Main

Summary

In this lab, you learned about POJOs and their role in Java programming. You learned how to create a POJO class and the difference between a POJO and a Java Bean class. You learned how to convert a POJO class to a Java Bean class and how to use Reflection API to view the properties of a Java Bean class. Finally, you learned how to serialize and deserialize a Java Bean object.

Other Java Tutorials you may like