protostuff
1.5.0
一個 Java 序列化函式庫,內建對向前向後相容性(模式演化)和驗證的支援。
有關更多信息,請訪問 https://protostuff.github.io/docs/
< dependency >
< groupId >io.protostuff</ groupId >
< artifactId >protostuff-core</ artifactId >
< version >1.7.4</ version >
</ dependency >
< dependency >
< groupId >io.protostuff</ groupId >
< artifactId >protostuff-runtime</ artifactId >
< version >1.7.4</ version >
</ dependency >
public final class Foo
{
String name ;
int id ;
public Foo ( String name , int id )
{
this . name = name ;
this . id = id ;
}
}
static void roundTrip ()
{
Foo foo = new Foo ( "foo" , 1 );
// this is lazily created and cached by RuntimeSchema
// so its safe to call RuntimeSchema.getSchema(Foo.class) over and over
// The getSchema method is also thread-safe
Schema < Foo > schema = RuntimeSchema . getSchema ( Foo . class );
// Re-use (manage) this buffer to avoid allocating on every serialization
LinkedBuffer buffer = LinkedBuffer . allocate ( 512 );
// ser
final byte [] protostuff ;
try
{
protostuff = ProtostuffIOUtil . toByteArray ( foo , schema , buffer );
}
finally
{
buffer . clear ();
}
// deser
Foo fooParsed = schema . newMessage ();
ProtostuffIOUtil . mergeFrom ( protostuff , fooParsed , schema );
}
如果純粹用它來替換java序列化(與protobuf不相容),請設定以下系統屬性:
-Dprotostuff.runtime.always_use_sun_reflection_factory=true
-Dprotostuff.runtime.preserve_null_elements=true
-Dprotostuff.runtime.morph_collection_interfaces=true
-Dprotostuff.runtime.morph_map_interfaces=true
-Dprotostuff.runtime.morph_non_final_pojos=true
您也可以透過程式設計方式自訂它:
static final DefaultIdStrategy STRATEGY = new DefaultIdStrategy ( IdStrategy . DEFAULT_FLAGS
| IdStrategy . PRESERVE_NULL_ELEMENTS
| IdStrategy . MORPH_COLLECTION_INTERFACES
| IdStrategy . MORPH_MAP_INTERFACES
| IdStrategy . MORPH_NON_FINAL_POJOS );
使用它:
Schema < Foo > schema = RuntimeSchema . getSchema ( Foo . class , STRATEGY );
Java 1.6 或更高版本
Maven 3.2.3 或更高版本
mvn install && mvn eclipse:eclipse
# Open eclipse, import existing project, navigate to the protostuff module you're after, then hit 'Finish'.