직렬화 가능이란 무엇입니까?
클래스가 Serializable
Java 로 존재한다는 것은 정확히 무엇을 의미 합니까? 또는 일반적으로 그 문제에 대해 ...
직렬화 는 예를 들어 디스크에 저장하기 위해 메모리에서 일련의 비트로 객체를 유지합니다. 역 직렬화는 반대입니다. 디스크에서 데이터를 읽어 객체를 수화 / 생성합니다.
귀하의 질문의 맥락에서, 클래스에서 구현되는 경우이 클래스는 다른 직렬 변환기에 의해 자동으로 직렬화 및 직렬화 해제 될 수있는 인터페이스입니다.
대부분의 사용자가 이미 답변을했지만 아이디어를 설명하기 위해 필요한 사람들을위한 예를 추가하고 싶습니다.
다음과 같은 클래스 사람이 있다고 가정 해 봅시다.
public class Person implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public String firstName;
public String lastName;
public int age;
public String address;
public void play() {
System.out.println(String.format(
"If I win, send me the trophy to this address: %s", address));
}
@Override
public String toString() {
return String.format(".....Person......\nFirst Name = %s\nLast Name = %s", firstName, lastName);
}
}
그런 다음 다음과 같은 객체를 만듭니다.
Person william = new Person();
william.firstName = "William";
william.lastName = "Kinaan";
william.age = 26;
william.address = "Lisbon, Portugal";
해당 개체를 여러 스트림으로 직렬화 할 수 있습니다. 나는 두 가지 흐름으로 그렇게 할 것입니다.
표준 출력으로 직렬화 :
public static void serializeToStandardOutput(Person person)
throws IOException {
OutputStream outStream = System.out;
ObjectOutputStream stdObjectOut = new ObjectOutputStream(outStream);
stdObjectOut.writeObject(person);
stdObjectOut.close();
outStream.close();
}
파일로 직렬화 :
public static void serializeToFile(Person person) throws IOException {
OutputStream outStream = new FileOutputStream("person.ser");
ObjectOutputStream fileObjectOut = new ObjectOutputStream(outStream);
fileObjectOut.writeObject(person);
fileObjectOut.close();
outStream.close();
}
그때:
파일에서 역 직렬화 :
public static void deserializeFromFile() throws IOException,
ClassNotFoundException {
InputStream inStream = new FileInputStream("person.ser");
ObjectInputStream fileObjectIn = new ObjectInputStream(inStream);
Person person = (Person) fileObjectIn.readObject();
System.out.println(person);
fileObjectIn.close();
inStream.close();
}
즉, 클래스의 인스턴스를 바이트 스트림으로 변환 한 다음 (예 : 파일로 저장) 다시 클래스로 다시 변환 할 수 있습니다. 이 리로딩은 프로그램의 다른 인스턴스 또는 다른 머신에서도 발생할 수 있습니다. 직렬화 (어떤 언어로든)는 특히 모든 직렬화 가능 오브젝트 내의 다른 오브젝트에 대한 참조가있는 경우 모든 종류의 문제를 포함합니다.
다음은 Serialization에 대한 자세한 설명입니다 . (나의 블로그)
직렬화 :
직렬화는 객체의 상태를 직렬화하는 프로세스로, 일련의 바이트 형식으로 표시되고 저장됩니다. 파일에 저장할 수 있습니다. 파일에서 객체의 상태를 읽고 복원하는 프로세스를 역 직렬화라고합니다.
What is the need of Serialization?
In modern day architecture, there is always a need to store object state and then retrieve it. For example in Hibernate, to store a object we should make the class Serializable. What it does, is that once the object state is saved in the form of bytes it can be transferred to another system which can then read from the state and retrieve the class. The object state can come from a database or a different jvm or from a separate component. With the help of Serialization we can retrieve the Object state.
Code Example and explanation:
First let's have a look at the Item Class:
public class Item implements Serializable{
/**
* This is the Serializable class
*/
private static final long serialVersionUID = 475918891428093041L;
private Long itemId;
private String itemName;
private transient Double itemCostPrice;
public Item(Long itemId, String itemName, Double itemCostPrice) {
super();
this.itemId = itemId;
this.itemName = itemName;
this.itemCostPrice = itemCostPrice;
}
public Long getItemId() {
return itemId;
}
@Override
public String toString() {
return "Item [itemId=" + itemId + ", itemName=" + itemName + ", itemCostPrice=" + itemCostPrice + "]";
}
public void setItemId(Long itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Double getItemCostPrice() {
return itemCostPrice;
}
public void setItemCostPrice(Double itemCostPrice) {
this.itemCostPrice = itemCostPrice;
}
}
In the above code it can be seen that Item class implements Serializable.
This is the interface that enables a class to be serializable.
Now we can see a variable called serialVersionUID is initialized to Long variable. This number is calculated by the compiler based on the state of the class and the class attributes. This is the number that will help the jvm identify the state of an object when it reads the state of the object from file.
For that we can have a look at the official Oracle Documentation:
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long: ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L; If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.
If you have noticed there is another keyword we have used which is transient.
If a field is not serializable, it must be marked transient. Here we marked the itemCostPrice as transient and don't want it to be written in a file
Now let's have a look on how to write the state of an object in the file and then read it from there.
public class SerializationExample {
public static void main(String[] args){
serialize();
deserialize();
}
public static void serialize(){
Item item = new Item(1L,"Pen", 12.55);
System.out.println("Before Serialization" + item);
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream("/tmp/item.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(item);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in /tmp/item.ser");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void deserialize(){
Item item;
try {
FileInputStream fileIn = new FileInputStream("/tmp/item.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
item = (Item) in.readObject();
System.out.println("Serialized data is read from /tmp/item.ser");
System.out.println("After Deserialization" + item);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
In the above we can see an example of serialization and deserialization of an object.
For that we used two classes. For serializing the object we have used ObjectOutputStream. We have used the method writeObject to write the object in the file.
For Deserializing we have used ObjectInputStream which reads from the object from the file. It uses readObject to read the object data from the file.
The output of the above code would be like:
Before SerializationItem [itemId=1, itemName=Pen, itemCostPrice=12.55]
Serialized data is saved in /tmp/item.ser
After DeserializationItem [itemId=1, itemName=Pen, itemCostPrice=null]
Notice that itemCostPrice from deserialized object is null as it was not written.
Serialization involves saving the current state of an object to a stream, and restoring an equivalent object from that stream. The stream functions as a container for the object
Serializable is called in like an interface but its more like a flag to the compiler. It says this object can be saved. All the Objects instance variables with the exception of none serializable objects and ones mark volatile will be saved.
Imagine your application can change colour as an option, without keeping that setting external you would need to change the colour every time you ran it.
Serialization is a technique to storing or writing the objects and data in to files. By using ObjectOutputStream
and FileOutputStream
classes. These classes having their specific methods to persist the objects. like writeObject();
for clear explantaion with figures . See Here for more info
To present from another perspective. Serialization is a kind of interface called 'marker interface'. A marker interface is an interface that contains no method declarations, but merely designates (or “marks”) a class that implements the interface as having some property. If you understand polymorphism this will make very much sense. In the case of the Serializable marker interface, the ObjectOutputStream.write(Object) method will fail if its argument does not implement the interface. This is a potential mistake in java, it could have been ObjectOutputStream.write(Serializable)
Highly Recommended : Reading Item 37 from Effective Java by Joshua Bloch to learn more.
Serialization: Writing State of Object to File/Network or anywhere. ( Mean Java Object Supported form to File Supported Form or Network Supported Form )
Deserialization: Reading State of Object from File/Network or anywhere. ( Mean File/Network Supported form to Java Object Supported Form )
Just to add to the other answers and with regards to generality. Serialization is sometimes known as archiving, for example in Objective-C.
참고URL : https://stackoverflow.com/questions/3429921/what-does-serializable-mean
'IT story' 카테고리의 다른 글
포크 / 조인 프레임 워크가 스레드 풀보다 나은 점은 무엇입니까? (0) | 2020.07.09 |
---|---|
$ .ajax-dataType (0) | 2020.07.09 |
Ubuntu 11.04에서 R 패키지를 설치할 수 없습니다. (0) | 2020.07.09 |
인라인과 외부 자바 스크립트는 언제 사용해야합니까? (0) | 2020.07.09 |
텍스트 파일을 Windows 명령 줄과 연결하여 선행 줄 삭제 (0) | 2020.07.09 |