Object serialization: Difference between revisions
Content added Content deleted
(→{{header|Go}}: library path update) |
(→{{header|Groovy}}: new solution) |
||
Line 740: | Line 740: | ||
yellow lab, not trained |
yellow lab, not trained |
||
trained collie, but doesn't catch frisbee</pre> |
trained collie, but doesn't catch frisbee</pre> |
||
=={{header|Groovy}}== |
|||
Sample Serializable Classes (borrowed from Java example. Sorta.): |
|||
<lang groovy>class Entity implements Serializable { |
|||
static final serialVersionUID = 3504465751164822571L |
|||
String name = 'Thingamabob' |
|||
public String toString() { return name } |
|||
} |
|||
class Person extends Entity implements Serializable { |
|||
static final serialVersionUID = -9170445713373959735L |
|||
Person() { name = 'Clement' } |
|||
Person(name) { this.name = name } |
|||
}</lang> |
|||
Writing objects: |
|||
<lang groovy>File objectStore = new File('objectStore.ser') |
|||
if (objectStore.exists()) { objectStore.delete() } |
|||
assert ! objectStore.exists() |
|||
def os |
|||
try { |
|||
os = objectStore.newObjectOutputStream() |
|||
os << new Person() |
|||
os << 10.5 |
|||
os << new Person('Cletus') |
|||
os << new Date() |
|||
os << new Person('Pious') |
|||
os << java.awt.Color.RED |
|||
os << new Person('Linus') |
|||
os << 'just random garbage' |
|||
os << new Person('Lucy') |
|||
os << ['lists', 'are', 'serializable'] |
|||
os << new Person('Schroeder') |
|||
} catch (e) { throw new Exception(e) } finally { os?.close() } |
|||
assert objectStore.exists()</lang> |
|||
Reading objects: |
|||
<lang groovy>def is |
|||
try { |
|||
is = objectStore.newObjectInputStream(this.class.classLoader) |
|||
is.eachObject { println it } |
|||
} catch (e) { throw new Exception(e) } finally { is?.close() } |
|||
objectStore.delete() |
|||
assert ! objectStore.exists()</lang> |
|||
Output: |
|||
<pre>Clement |
|||
10.5 |
|||
Cletus |
|||
Wed Jan 18 02:07:29 CST 2012 |
|||
Pious |
|||
java.awt.Color[r=255,g=0,b=0] |
|||
Linus |
|||
just random garbage |
|||
Lucy |
|||
[lists, are, serializable] |
|||
Schroeder</pre> |
|||
=={{header|J}}== |
=={{header|J}}== |