01 /*
02 * Java Genetic Algorithm Library (jenetics-5.1.0).
03 * Copyright (c) 2007-2019 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19 */
20 package io.jenetics.ext.util;
21
22 import java.io.Externalizable;
23 import java.io.IOException;
24 import java.io.ObjectInput;
25 import java.io.ObjectOutput;
26 import java.io.StreamCorruptedException;
27
28 /**
29 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
30 * @version 5.0
31 * @since 5.0
32 */
33 final class Serial implements Externalizable {
34
35 private static final long serialVersionUID = 1;
36
37 static final byte TREE_NODE = 1;
38 static final byte FLAT_TREE_NODE = 2;
39
40 /**
41 * The type being serialized.
42 */
43 private byte _type;
44
45 /**
46 * The object being serialized.
47 */
48 private Object _object;
49
50 /**
51 * Constructor for deserialization.
52 */
53 public Serial() {
54 }
55
56 /**
57 * Creates an instance for serialization.
58 *
59 * @param type the type
60 * @param object the object
61 */
62 Serial(final byte type, final Object object) {
63 _type = type;
64 _object = object;
65 }
66
67 @Override
68 public void writeExternal(final ObjectOutput out) throws IOException {
69 out.writeByte(_type);
70 switch (_type) {
71 case TREE_NODE: ((TreeNode)_object).write(out); break;
72 case FLAT_TREE_NODE: ((FlatTreeNode)_object).write(out); break;
73 default:
74 throw new StreamCorruptedException("Unknown serialized type.");
75 }
76 }
77
78 @Override
79 public void readExternal(final ObjectInput in)
80 throws IOException, ClassNotFoundException
81 {
82 _type = in.readByte();
83 switch (_type) {
84 case TREE_NODE: _object = TreeNode.read(in); break;
85 case FLAT_TREE_NODE: _object = FlatTreeNode.read(in); break;
86 default:
87 throw new StreamCorruptedException("Unknown serialized type.");
88 }
89 }
90
91 private Object readResolve() {
92 return _object;
93 }
94
95 }
|