Java native language to want a custom class serializable, very simple, Just let this class implement the Java.io.Serializable interface, but in the Hadoop framework, to allow the custom class to be serialized, we have to manually implement the Writablecompable interface and implement write (). ReadFields (), CompareTo () method.
The following is a serializable class that we can customize:
* */package com.charles.writable;
Import Java.io.DataInput;
Import Java.io.DataOutput;
Import java.io.IOException;
Import org.apache.hadoop.io.IntWritable;
Import Org.apache.hadoop.io.Text;
Import org.apache.hadoop.io.WritableComparable; /** * * Description: This is a custom Hadoop serialization class that can serialize this class with Hadoop serialization * * @author Charles.wang * @created June 2, 2012 11:19 : AM * * * * public class Personwritable implements writablecomparable<personwritable> {private Tex
T name;
Private intwritable age;
Private Text title;
Public personwritable () {Set ("Someperson", 0, "Sometitle");
Personwritable (string name, int age, string title) {Set (Name,age,title);
public void Set (String name, int age,string title) {this.name = new Text (name);
Age= (age>0) age:1;
This.age = new intwritable (age); this.title= new Text (title); /** * This method is used to define the serialization process, which serializes all the fields of the object in turn/@Override public void Write (Data
Output out) throws IOException {//TODO auto-generated a stub name.write (out);
Age.write (out);
Title.write (out); /** * This method defines the deserialization process, which restores the serialized datainput content to the Hadoop object/@Override public void Readfield S (Datainput in) throws IOException {//TODO auto-generated a stub name.readfields (in
);
Age.readfields (in);
Title.readfields (in);
/** * This is a comparison between 2 serialized objects */@Override public int compareTo (personwritable pO) {
TODO auto-generated Method Stub int cmp1 = Name.compareto (po.name);
if (cmp1!= 0) {return cmp1;
int cmp2 = Age.compareto (po.age); if (cmp2!=0) {return cmp2;
int Cmp3 = Title.compareto (Po.title);
return Cmp3; /** * Definition hashcode is a good habit, we still use the most commonly used fields multiplied by different primes and then add the method * * @Override public int hashcode ()
{return Name.hashcode () *71+ Age.hashcode () *73+title.hashcode () *127;
@Override public boolean equals (Object o) {if (o instanceof personwritable) {
Personwritable pw = (personwritable) o;
Boolean equals = Name.equals (pw.name) && age.equals (pw.age) && title.equals (pw.title);
return equals;
return false;
@Override public String toString () {stringbuffer sb = new StringBuffer ();
Sb.append ("[");
Sb.append ("Name:" +name+ ",");
Sb.append ("Age:" +age+ ",");
Sb.append ("title:" +title);
Sb.append ("]"); Return SB.TOSTRING (); }
}