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.op;
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 4.1
32 * @since 4.1
33 */
34 final class SerialProxy implements Externalizable {
35
36 @Serial
37 private static final long serialVersionUID = 1L;
38
39 static final byte MATH_EXPR = 1;
40 static final byte CONST = 2;
41 static final byte EPHEMERAL_CONST = 3;
42
43 /**
44 * The type being serialized.
45 */
46 private byte _type;
47
48 /**
49 * The object being serialized.
50 */
51 private Object _object;
52
53 /**
54 * Constructor for deserialization.
55 */
56 public SerialProxy() {
57 }
58
59 /**
60 * Creates an instance for serialization.
61 *
62 * @param type the type
63 * @param object the object
64 */
65 SerialProxy(final byte type, final Object object) {
66 _type = type;
67 _object = object;
68 }
69
70 @Override
71 public void writeExternal(final ObjectOutput out) throws IOException {
72 out.writeByte(_type);
73 switch (_type) {
74 case MATH_EXPR -> ((MathExpr)_object).write(out);
75 case CONST -> ((Const<?>)_object).write(out);
76 case EPHEMERAL_CONST -> ((EphemeralConst<?>)_object).write(out);
77 default -> throw new StreamCorruptedException("Unknown serialized type.");
78 }
79 }
80
81 @Override
82 public void readExternal(final ObjectInput in)
83 throws IOException, ClassNotFoundException
84 {
85 _type = in.readByte();
86 _object = switch (_type) {
87 case MATH_EXPR -> MathExpr.read(in);
88 case CONST -> Const.read(in);
89 case EPHEMERAL_CONST -> EphemeralConst.read(in);
90 default -> throw new StreamCorruptedException("Unknown serialized type.");
91 };
92 }
93
94 @Serial
95 private Object readResolve() {
96 return _object;
97 }
98
99 }
|