01 /*
02 * Java Genetic Algorithm Library (jenetics-7.1.0).
03 * Copyright (c) 2007-2022 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.prog;
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.Serial;
27 import java.io.StreamCorruptedException;
28
29 /**
30 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
31 * @version 5.0
32 * @since 5.0
33 */
34 final class SerialProxy implements Externalizable {
35
36 @Serial
37 private static final long serialVersionUID = 1;
38
39 static final byte PROGRAM_CHROMOSOME = 1;
40
41 /**
42 * The type being serialized.
43 */
44 private byte _type;
45
46 /**
47 * The object being serialized.
48 */
49 private Object _object;
50
51 /**
52 * Constructor for deserialization.
53 */
54 public SerialProxy() {
55 }
56
57 /**
58 * Creates an instance for serialization.
59 *
60 * @param type the type
61 * @param object the object
62 */
63 SerialProxy(final byte type, final Object object) {
64 _type = type;
65 _object = object;
66 }
67
68 @Override
69 public void writeExternal(final ObjectOutput out) throws IOException {
70 out.writeByte(_type);
71 switch (_type) {
72 case PROGRAM_CHROMOSOME -> ((ProgramChromosome)_object).write(out);
73 default -> throw new StreamCorruptedException("Unknown serialized type.");
74 }
75 }
76
77 @Override
78 public void readExternal(final ObjectInput in)
79 throws IOException, ClassNotFoundException
80 {
81 _type = in.readByte();
82 _object = switch (_type) {
83 case PROGRAM_CHROMOSOME -> ProgramChromosome.read(in);
84 default -> throw new StreamCorruptedException("Unknown serialized type.");
85 };
86 }
87
88 @Serial
89 private Object readResolve() {
90 return _object;
91 }
92
93 }
|