-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.txt
43 lines (22 loc) · 6.09 KB
/
test.txt
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
При сериализации объекта в Java с интерфейсом есть важное обстоятельство, которое нужно учитывать. В процессе сериализации сохраняется не только состояние объекта, но и информация о типе объекта (так называемая метаинформация). По умолчанию Java сохраняет имя класса объекта и его серийный номер (serialVersionUID).
Когда вы сериализуете объект, реализующий интерфейс, Java сохраняет имя класса этого объекта. В случае передачи объекта через сеть, на стороне клиента необходимо, чтобы класс, соответствующий этому имени, был доступен. Если класс отсутствует, возникает исключение `ClassNotFoundException`.
Чтобы избежать этой проблемы, необходимо убедиться, что все классы, используемые при сериализации и десериализации, доступны как на стороне сервера, так и на стороне клиента. Это может потребовать, например, упаковки всех необходимых классов в JAR-файл и передачи его вместе с приложением.
Теперь рассмотрим процесс сериализации и десериализации поэтапно:
### Сериализация:
1. **Подготовка объекта**: Объект, который вы хотите передать по сети, должен быть экземпляром класса, который реализует интерфейс `Serializable`.
2. **Создание потока вывода**: Вы создаете `ObjectOutputStream`, который является потоком вывода, способным записывать объекты Java в поток байтов.
3. **Запись объекта**: Вы вызываете `writeObject()` на вашем `ObjectOutputStream`, чтобы записать объект в поток.
### Десериализация:
1. **Создание потока ввода**: Вы создаете `ObjectInputStream`, который является потоком ввода, способным читать объекты Java из потока байтов.
2. **Чтение объекта**: Вы вызываете `readObject()` на вашем `ObjectInputStream`, чтобы прочитать объект из потока.
3. **Приведение типа объекта**: Полученный объект имеет тип `Object`, поэтому вам нужно привести его к правильному типу перед использованием.
Во время десериализации Java использует метаинформацию о классе объекта (имя класса и serialVersionUID), чтобы найти соответствующий класс и создать объект этого класса. Если класс недоступен, возникает исключение `ClassNotFoundException`.
Чтобы избежать этой ошибки, убедитесь, что все необходимые классы доступны как на стороне сервера, так и на стороне клиента.
При сериализации объекта в Java метод `writeObject()` класса `ObjectOutputStream` анализирует структуру объекта и сериализует его в соответствии с определенными правилами. Вот как это происходит:
1. **Поля объекта**: ObjectOutputStream сериализует все нестатические и не транзиентные поля объекта. Транзиентные поля (объявленные с ключевым словом `transient`) исключаются из сериализации.
2. **Поля суперкласса**: Если объект наследуется от другого класса, ObjectOutputStream также сериализует все нестатические и не транзиентные поля суперкласса.
3. **Вложенные объекты**: Если у объекта есть ссылки на другие объекты, ObjectOutputStream рекурсивно сериализует их.
4. **Статические поля и методы**: ObjectOutputStream не сериализует статические поля и методы, так как они принадлежат классу, а не конкретному объекту.
5. **Метаданные**: ObjectOutputStream также сохраняет метаданные о классе объекта, включая его имя класса и версию serialVersionUID. Эта метаинформация позволяет десериализатору определить, как правильно воссоздать объект из потока байтов.
При десериализации объекта ObjectInputStream использует эту метаинформацию и структуру байтов для воссоздания объекта в памяти.
Таким образом, ObjectOutputStream "понимает", как сериализовать объект, путем обхода его структуры и сериализации каждого поля, включая вложенные объекты, и сохранения метаданных о классе. Этот процесс автоматический и требует минимального вмешательства программиста.