Sometimes developers need to store their Java class object in database. This tip demonstrate how we can store object into database and again access the stored Java object.
//Creating a simple class.
public class SimpleExample implements Serializable{
//Member variable.
private int intValue;
private String string;
public void setIntValue(int intValue){
this.intValue = intValue;
}
public void setString(String string){
this.string = string;
}
public int getIntValue(){
return this.intValue;
}
public String getString(){
return this.string;
}
}
/*
* creating a class which have two function getByteArrayObject and getJavaObject.
*
* getByteArrayObject convert java object into byte[] and return the byte[].
*
* getJavaObject convert byte[] to java object. and return SimpleExample object.
*
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ConvertObject {
//converting SimpleExample object to byte[].
public byte[] getByteArrayObject(SimpleExample simpleExample){
byte[] byteArrayObject = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(simpleExample);
oos.close();
bos.close();
byteArrayObject = bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return byteArrayObject;
}
return byteArrayObject;
}
//converting byte[] to SimpleExample
public SimpleExample getJavaObject(byte[] convertObject){
SimpleExample objSimpleExample = null;
ByteArrayInputStream bais;
ObjectInputStream ins;
try {
bais = new ByteArrayInputStream(convertObject);
ins = new ObjectInputStream(bais);
objSimpleExample =(SimpleExample)ins.readObject();
ins.close();
}
catch (Exception e) {
e.printStackTrace();
}
return objSimpleExample;
}
}