Memo オブジェクトと文字列の変換
カブロボは日をまたいでの独自ユーザデータの引渡しに「Memo」を利用する。
Memoは文字列型なので、オブジェクトを保存したい場合は、以下のようなオブジェクトと文字列と変換するクラスを作るとよいと思われる。
この例では、デフォルトのシリアライズを利用している。
package hoge;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
public class Memento implements Serializable{
final static String ENCODE = "ISO8859-1";
private int day;
public static Memento createMemento(String memo) throws Exception{ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(memo.getBytes(ENCODE))
);
Memento memento = (Memento)in.readObject();
in.close();
return memento;
}
public String toMemo() throws IOException{
ByteArrayOutputStream ba = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(ba);
out.writeObject(this);
out.close();
String memo = ba.toString(ENCODE);
return memo;
}
public int getDay() {
return day;
}public void setDay(int day) {
this.day = day;
}
public void countDay(){
day++;
}
//てすと
public static void main(String[] args) throws Exception{
try{
Memento memento = new Memento();
memento.countDay();
String memo = memento.toMemo();
memento = Memento.createMemento(memo);
System.out.println(memento);
}catch(StreamCorruptedException e){
e.printStackTrace();
}
}
}
あるいは、JDK1.4のXMLEncoder/Decoderを利用することもできる。
シリアライズと異なり、どんな風に保存されたか確認しやすい。
ただし保存する値は、プロパティー(セッタ、ゲッタあるやつ)のみ。
package hoge;import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.io.StreamCorruptedException;
public class Memento2 implements Serializable{
final static String ENCODE = "UTF-8";
private int day;
public static Memento2 createMemento(String memo) throws Exception{
XMLDecoder decoder = new XMLDecoder(
new ByteArrayInputStream(memo.getBytes(ENCODE)
));
Memento2 memento = (Memento2)decoder.readObject();
decoder.close();
return memento;
}
public String toMemo() throws IOException{
ByteArrayOutputStream ba = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(ba);
encoder.writeObject(this);
encoder.close();
String memo = ba.toString(ENCODE);
System.out.println(memo);
return memo;
}
public int getDay() {
return day;
}public void setDay(int day) {
this.day = day;
}
public void countDay(){
day++;
}
//てすと
public static void main(String[] args) throws Exception{
try{
Memento2 memento = new Memento2();
memento.countDay();
String memo = memento.toMemo();
memento = Memento2.createMemento(memo);
System.out.println(memento);
System.out.println("OK");
}catch(StreamCorruptedException e){
e.printStackTrace();
}
}
}
でも、うちのロボットは「Memo」使わないかも。。。