Serialization and Reflection in Java

Last updated on Dec 27 2022
Prabhas Ramanathan

Java provides a mechanism, called object serialization where 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.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out −
public final void writeObject(Object x) throws IOException
The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object −
public final Object readObject() throws IOException, ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.
To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface −

Table of Contents

Example

public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;

public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
}

Notice that for a class to be serialized successfully, two conditions must be met −
• The class must implement the java.io.Serializable interface.
• All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.
If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it’s not.

Serializing an Object

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.
Note − When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.
Example

import java.io.*;
public class SerializeDemo {

public static void main(String [] args) {
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;

try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}

Deserializing an Object

The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output −

Example

import java.io.*;
public class DeserializeDemo {

public static void main(String [] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}

System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}

 

This will produce the following result −
Output

Deserialized Employee…
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

Here are following important points to be noted −
• The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can’t find a class during the deserialization of an object, it throws a ClassNotFoundException.
• Notice that the return value of readObject() is cast to an Employee reference.
• The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0.

Java Reflection API

Java Reflection is a process of examining or modifying the run time behavior of a class at run time.
The java.lang.Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.
The java.lang and java.lang.reflect packages provide classes for java reflection.

Where it is used

The Reflection API is mainly used in:
• IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
• Debugger
• Test Tools etc.

java.lang.Class class

The java.lang.Class class performs mainly two tasks:
• provides methods to get the metadata of a class at run time.
• provides methods to examine and change the run time behavior of a class.

Commonly used methods of Class class:

Method Description
1) public String getName() returns the class name
2) public static Class forName(String className)throws ClassNotFoundException loads the class and returns the reference of Class class.
3) public Object newInstance()throws InstantiationException,IllegalAccessException creates new instance.
4) public boolean isInterface() checks if it is interface.
5) public boolean isArray() checks if it is array.
6) public boolean isPrimitive() checks if it is primitive.
7) public Class getSuperclass() returns the superclass class reference.
8) public Field[] getDeclaredFields()throws SecurityException returns the total number of fields of this class.
9) public Method[] getDeclaredMethods()throws SecurityException returns the total number of methods of this class.
10) public Constructor[] getDeclaredConstructors()throws SecurityException returns the total number of constructors of this class.
11) public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException returns the method class instance.

How to get the object of Class class?

There are 3 ways to get the instance of Class class. They are as follows:
• forName() method of Class class
• getClass() method of Object class
• the .class syntax

1) forName() method of Class class

• is used to load the class dynamically.
• returns the instance of Class class.
• It should be used if you know the fully qualified name of class.This cannot be used for primitive types.
Let’s see the simple example of forName() method.

1. class Simple{} 
2. 
3. class Test{ 
4. public static void main(String args[]){ 
5. Class c=Class.forName("Simple"); 
6. System.out.println(c.getName()); 
7. } 
8. }

Simple

2) getClass() method of Object class

It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives.

1. class Simple{} 
2. 
3. class Test{ 
4. void printName(Object obj){ 
5. Class c=obj.getClass(); 
6. System.out.println(c.getName()); 
7. } 
8. public static void main(String args[]){ 
9. Simple s=new Simple(); 
10. 
11. Test t=new Test(); 
12. t.printName(s); 
13. } 
14. } 
15.

Simple

 

3) The .class syntax

If a type is available but there is no instance then it is possible to obtain a Class by appending “.class” to the name of the type.It can be used for primitive data type also.

1. class Test{ 
2. public static void main(String args[]){ 
3. Class c = boolean.class; 
4. System.out.println(c.getName()); 
5. 
6. Class c2 = Test.class; 
7. System.out.println(c2.getName()); 
8. } 
9. }

boolean
Test

 

Determining the class object

Following methods of Class class is used to determine the class object:
1) public boolean isInterface(): determines if the specified Class object represents an interface type.
2) public boolean isArray(): determines if this Class object represents an array class.
3) public boolean isPrimitive(): determines if the specified Class object represents a primitive type.

Let’s see the simple example of reflection api to determine the object type.

1. class Simple{} 
2. interface My{} 
3. 
4. class Test{ 
5. public static void main(String args[]){ 
6. try{ 
7. Class c=Class.forName("Simple"); 
8. System.out.println(c.isInterface()); 
9. 
10. Class c2=Class.forName("My"); 
11. System.out.println(c2.isInterface()); 
12. 
13. }catch(Exception e){System.out.println(e);} 
14. 
15. } 
16. }

false
true

So, this brings us to the end of blog. This Tecklearn ‘Serialization and Reflection in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Serialization and Reflection in Java"

Leave a Message

Your email address will not be published. Required fields are marked *