Skip to content

Instantly share code, notes, and snippets.

@frsyuki
Created September 24, 2010 11:18
Show Gist options
  • Save frsyuki/595206 to your computer and use it in GitHub Desktop.
Save frsyuki/595206 to your computer and use it in GitHub Desktop.
// org.msgpack.Packer クラス
public Packer pack(Object o) throws IOException {
if(o == null) {
return packNil();
} else if(o instanceof String) {
byte[] b = ((String)o).getBytes("UTF-8");
packRaw(b.length);
return packRawBody(b);
} else if(o instanceof MessagePackable) {
((MessagePackable)o).messagePack(this);
return this;
} else if(o instanceof byte[]) {
byte[] b = (byte[])o;
packRaw(b.length);
return packRawBody(b);
} else if(o instanceof List) {
List<Object> l = (List<Object>)o;
packArray(l.size());
for(Object i : l) { pack(i); }
return this;
} else if(o instanceof Map) {
Map<Object,Object> m = (Map<Object,Object>)o;
packMap(m.size());
for(Map.Entry<Object,Object> e : m.entrySet()) {
pack(e.getKey());
pack(e.getValue());
}
return this;
} else if(o instanceof Boolean) {
if((Boolean)o) {
return packTrue();
} else {
return packFalse();
}
} else if(o instanceof Integer) {
return packInt((Integer)o);
} else if(o instanceof Long) {
return packLong((Long)o);
} else if(o instanceof Short) {
return packShort((Short)o);
} else if(o instanceof Byte) {
return packByte((Byte)o);
} else if(o instanceof Float) {
return packFloat((Float)o);
} else if(o instanceof Double) {
return packDouble((Double)o);
} else if(o instanceof BigInteger) {
return packBigInteger((BigInteger)o);
} else {
// { ここ追加
MessagePackPacker packer = CustomPacker.getRegistered(o.getClass()); // CustomPackerの命名は要検討
if(packer != null) {
return packer.pack(this, o);
}
// } ここまで
throw new MessageTypeException("unknown object "+o+" ("+o.getClass()+")");
}
}
// このクラス追加
public class CustomPacker {
public MessagePackPacker getRegistered(Class) { ... }
public boolean isRegistered(Class) { ... }
public void register(Class, MessagePackPacker) { ... }
public MessagePackPacker registerReflection(Class c) { // リフレクションと見せかけてコード生成
MessagePackPacker packer = PackUnpackUtil.generatePacker(c); // コード生成
register(c, packer);
return packer;
}
}
// org.msgpack.PackUnpackUtil$Enhancer クラス
// enhancedクラスを生成する部分とpacker/unpackerクラスを生成する部分を分離
// packer/unpackerクラスを生成・キャッシュする器部分:
MessagePackPacker packer = CustomPacker.registerReflection(obj.getClass());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment