forked from DNAProject/DNA-java-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerializable.java
More file actions
44 lines (39 loc) · 1.22 KB
/
Copy pathSerializable.java
File metadata and controls
44 lines (39 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package DNA.IO;
import java.io.*;
/**
* 为序列化提供一个接口
*/
public interface Serializable {
/**
* 反序列化
* <param name="reader">数据来源</param>
* @throws IOException
*/
void deserialize(BinaryReader reader) throws IOException;
/**
* 序列化
* <param name="writer">存放序列化后的结果</param>
* @throws IOException
*/
void serialize(BinaryWriter writer) throws IOException;
default byte[] toArray() {
try (ByteArrayOutputStream ms = new ByteArrayOutputStream()) {
try (BinaryWriter writer = new BinaryWriter(ms)) {
serialize(writer);
writer.flush();
return ms.toByteArray();
}
} catch (IOException ex) {
throw new UnsupportedOperationException(ex);
}
}
static <T extends Serializable> T from(byte[] value, Class<T> t) throws InstantiationException, IllegalAccessException {
try (ByteArrayInputStream ms = new ByteArrayInputStream(value)) {
try (BinaryReader reader = new BinaryReader(ms)) {
return reader.readSerializable(t);
}
} catch (IOException ex) {
throw new IllegalArgumentException(ex);
}
}
}