Java Program to Convert Byte Array to Object
Last Updated :
02 Feb, 2022
Converting byte array into Object and Object into a byte array process is known as deserializing and serializing. The class object which gets serialized/deserialized must implement the interface Serializable.
- Serializable is a marker interface that comes under package ‘java.io.Serializable’.
- Byte Array: Byte Array is only used to store byte data type values. The default value of the elements in a byte array is 0.
- Object: User-defined data type.
For serialized/deserialized, we use class SerializationUtils.
Approach (Using SerializationUtils class)
- Serializing and deserializing are two main functions of this class.
- This class comes under package ‘org.apache.commons.lang3‘.
Serializing (converting Object into a byte array)
Syntax:
public static byte[] serialize(Serializable object)
Parameter: An object that the user wants to serialize.
Returns: Function will return byte array.
Deserializing (converting byte array into Object)
Syntax:
public static Object deserialize(byte[] objectByteArray)
Parameter: Serialized Byte Array.
Returns: Function will return Object.
Example:
Java
import java.io.*;
import org.apache.commons.lang3.*;
class gfgStudent implements Serializable {
public int rollNumber;
public String name;
public char gender;
public gfgStudent( int rollNumber, String name,
char gender)
{
this .rollNumber = rollNumber;
this .name = name;
this .gender = gender;
}
}
class gfgMain {
public static void main(String arg[])
{
gfgStudent student;
student = new gfgStudent( 101 , "Harsh" , 'M' );
byte byteArray[]
= SerializationUtils.serialize(student);
gfgStudent newStudent;
newStudent
= (gfgStudent)SerializationUtils.deserialize(
byteArray);
System.out.println( "Deserialized object" );
System.out.println(newStudent.rollNumber);
System.out.println(newStudent.name);
System.out.println(newStudent.gender);
}
}
|
Output :
Share your thoughts in the comments
Please Login to comment...