Serialize
μ§λ ¬νλ ?
μ§λ ¬νλ Java
μμ€ν
λ΄λΆμμ μ¬μ©λλ Object
λλ Data
λ₯Ό μΈλΆμ Java
κΈ°λ° μμ€ν
μμλ μ¬μ©ν μ μλλ‘ byte
ννμ λ°μ΄ν°λ‘ λ³ννλ κΈ°μ
μ΄λ JVM (Java Virtual Machine) μ΄ λ©λͺ¨λ¦¬μ μμ£Ό (Heap λλ Stack) λμ΄ μλ Object
λ°μ΄ν°λ₯Ό byte ννλ‘ λ³ννλ€.
μμ§λ ¬ν
byte
μ½λλ‘ λμ΄ μλ Data λ₯Ό μλλλ‘ Object νΉμ Data λ‘ λ³ννλ κΈ°μ μ λ§νλ€.
μ΄λ λ€μ λ§ν΄ μ§λ ¬νλ λ°μ΄ν°λ₯Ό Object λ‘ λ³νν΄μ JVM λ΄λΆμ μμ£Ό μν€λκ² μ΄λ€.
μ§λ ¬ν νκΈ°
Serializable μ΄λΌλ λ§μ»€ μΈν°νμ΄μ€λ₯Ό μμνμ¬ κ΅¬ννλ€.
μ§λ ¬ν 쑰건
java.io.Serializable
μΈν°νμ΄μ€λ₯Ό ꡬνν ννλ‘ μμ
νλ€.
public void serializable() {
Member member = new Member("κΉλͺ
μ", 10);
byte[] serializable;
String serialStr = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(member);
serializable = baos.toByteArray();
serialStr = Base64.getEncoder().encodeToString(serializable);
System.out.println(serialStr);
} catch (Exception e) {
e.printStackTrace();
}
byte[] seraialDecode = Base64.getDecoder().decode(serialStr);
ByteArrayInputStream bais = new ByteArrayInputStream(seraialDecode);
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
Object objMember = ois.readObject();
Member om = (Member) objMember;
System.out.println(om.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
static class Member implements Serializable {
private static String name;
private static int age;
public Member(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return String.format("μ΄λ¦ : %s, λμ΄ : %d", name, age);
}
}
transient
ν€μλ
transient
ν€μλλ₯Ό λΆμ΄ λ³μλ μ§λ ¬ν λμμμ μ μΈλλ€.
λ°μ΄ν°λ₯Ό λμ€ν¬μ μ μ₯νκ±°λ λλΉμ μ μ₯ν λ Http Request λ₯Ό ν΅ν΄ ν΅μ νλ κ²½μ° λ―Όκ°μ 보 (κ°μΈμ 보λ₯Ό ν¬ν¨ν λΉλ°λ²νΈμ κ°μ μ 보λ€) μ μ μΈνκ³ μΆμΌλ©΄ transient
μ λΆμ¬μ μ¬μ©νλ©΄ λλ€.
JPA λͺ¨λΈμ κ²½μ° @transient
μ΄λ
Έν
μ΄μ
μ ν΅ν΄ DB κ°κ³Ό 맀ν μν€μ§ μλλ€.
public class User implements Serializable {
private static final long serialVersionUID = 100000000000000001L;
private String username;
private transient String passWord;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
public class UserTest {
@Test
public void transientField() throws IOException, ClassNotFoundException {
final User user = new User("rrest", "1234");
final FileOutputStream fos = new FileOutputStream("/tmp/user");
final ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(user);
oos.flush();
oos.close();
fos.close();
final FileInputStream fis = new FileInputStream("/tmp/user");
final ObjectInputStream ois = new
}
}
β Type Token Intersection Type β