Let's implement a marshaller for a simple class and check its influence on the performance.
We will marshal the following class:
01/* Copyright (C) 2007 db4objects Inc. http://www.db4o.com */ 02
package com.db4odoc.marshal; 03
04
public class Item{ 05
06
public int _one; 07
08
public long _two; 09
10
public int _three; 11
12
public Item(int one, long two, int three) { 13
_one = one; 14
_two = two; 15
_three = three; 16
17
} 18
19
public Item() { 20
21
} 22
23
public String toString() { 24
return String.format("%h, %h, %d", _one, _two, _three); 25
} 26
27
}
The marshaller - ItemMarshaller - will need to implement writeFields, readFields and marshalledFieldLength methods.
As Item class has only int and long fields we can use PrimitiveCodec class to write the fields to the byte array:
01/* Copyright (C) 2007 db4objects Inc. http://www.db4o.com */ 02
package com.db4odoc.marshal; 03
04
import com.db4o.config.ObjectMarshaller; 05
import com.db4o.foundation.PrimitiveCodec; 06
07
public class ItemMarshaller implements ObjectMarshaller{ 08
09
// Write field values to a byte array 10
// No reflection is used 11
public void writeFields(Object obj, byte[] slot, int offset) { 12
Item item = (Item)obj; 13
PrimitiveCodec.writeInt(slot, offset, item._one); 14
offset+= PrimitiveCodec.INT_LENGTH; 15
PrimitiveCodec.writeLong(slot, offset, item._two); 16
offset+= PrimitiveCodec.LONG_LENGTH; 17
PrimitiveCodec.writeInt(slot, offset, item._three); 18
} 19
20
// Restore field values from the byte array 21
// No reflection is used 22
public void readFields(Object obj, byte[] slot, int offset) { 23
Item item = (Item)obj; 24
item._one = PrimitiveCodec.readInt(slot, offset); 25
offset+= PrimitiveCodec.INT_LENGTH; 26
item._two = PrimitiveCodec.readLong(slot, offset); 27
offset+= PrimitiveCodec.LONG_LENGTH; 28
item._three = PrimitiveCodec.readInt(slot, offset); 29
} 30
31
public int marshalledFieldLength() { 32
return PrimitiveCodec.INT_LENGTH * 2 + PrimitiveCodec.LONG_LENGTH; 33
} 34
}