Thrift is used for cross platform communication. Only if thrift object is serialized it can be passed on to different platforms. In the destination it has to be deserialized for using it. Now let’s see thrift serialization and deserialization.
Jars needed are,
· slf4j-api-1.5.6.jar
· slf4j-simple-1.5.6.jar
· thrift.jar
Creating Thrift file:
Please click this link – Create Thrift File
Once you have created the thrift file, please copy Employee.java file.
Class name: TestThrift.java
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
public class TestThrift {
public static void main(String args[]) {
//Creating object for thrift generated java file
Employee emp = new Employee();
//Add the values to the above object
emp.setId("1");
emp.setName("SAM");
emp.setAddress("MY HOME");
emp.setPhoneNumber("0123456789");
//To send this across different platforms like DOTNET etc...
//this object needs to be serialized
//The serialized thrift object is nothing but a byte array
byte[] empDtl = null;
TSerializer serializer = new TSerializer();
try {
empDtl = serializer.serialize(emp);
} catch (TException e) {
e.printStackTrace();
}
//This serialized object can be send to any platform
//Deserializing it in the destination platform
//will give thrift file compatible for the destination platform
System.out.println("Serialized thrift object : "+empDtl);
//Deserializing thrift object
TDeserializer deserializer = new TDeserializer();
Employee empNew = new Employee();
//deserializer.deserialize(thrift object, byte array);
//When you deserialize the byte array is converted to the
//thrift object that is passed as a parameter to this method
try {
deserializer.deserialize(empNew, empDtl);
} catch (TException e) {
e.printStackTrace();
}
//Printing the deserialized thrift file
System.out.println("Deserialized thrift object"+empNew);
}
}
OUTPUT:
Serialized thrift object : [B@1a5f739
Deserialized thrift object: Employee(id:1, name:SAM, address:MY HOME, phoneNumber:0123456789)
Where is the Employee.java you are referring to?
ReplyDeleteClick on the "Employee.java" in this page, that will give you the required file.
Delete