Firstly why we need custom serialization ?.
.look😁 we we serialized the object there may the chance of loosing some information due to the transient keyword,to overcome this problem we go for custom serialization.
For custom serialization we have to override the writeOjbect() method and inside the method we have to encrypt the information.
custom.java
package Serializations;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class custom implements Serializable {
String uname="praveen";
transient String pass="India";
transient int pin=1235;
private void writeObject(ObjectOutputStream oos) throws IOException
{
oos.defaultWriteObject();
String epass="123"+pass;
int epin=2222+pin;
oos.writeObject(epass);
oos.writeInt(epin);
}
private void readObject(ObjectInputStream ois) throws Exception
{
ois.defaultReadObject();
String rrpass=(String)ois.readObject();
pass=rrpass.substring(3);
int epin=ois.readInt();
pin=epin-2222;
}
}
Demo.java
package Serializations;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Demo implements Serializable{
public static void main(String[] args) throws IOException, ClassNotFoundException {
custom d = new custom();
FileOutputStream fos = new FileOutputStream("serial.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream fis = new FileInputStream("serial.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
custom d2=(custom)ois.readObject();
System.out.println(d2.uname+"...."+ d2.pass +"..."+ d2.pin);
}
}
When you run Demo class.Output would be:
praveen....India...1235.
and serial.ser file will be create inside classpath.
No comments:
Post a Comment