티스토리 뷰

정리하기/개발 기본

직렬화

내가송 2024. 1. 17. 22:43
반응형

직렬화(Serialization) 

객체의 상태를 연속적인 데이터 형태로 변환하는 과정 

 

파일 시스템에 객체를 저장하고 로드, 다른 시스템이나 애플리케이션 간에 데이터를 공유할 때 객체 직렬화 과정이 필요하다. 

 

객체 직렬화를 지원하는게 Serializable 과 Parcelable 인터페이스가 있다. 

그렇다면 Serializable 과 Parcelable 은 어떤 차이가 있을까? 

 

Serializable 

자바에서 지원하는 방식으로 리플렉션을 사용하여 직렬화를 하기 때문에

상대적으로 속도가 느리고 추가적인 메모리를 사용할 수 있다. 

 

Serializable 인터페이스를 추가 후 추가 메소드를 구현하지 않아도 되어 구현이 간편하다. 

 

Parcelable

안드로이드 프레임워크에 특화되어 액티비티 간 intent 로 데이터를 전달할 때 사용한다.

 

리플렉션을 사용하지 않고 안드로이드의 IPC(Inter-Process Communication) 매커니즘에 최적화 되어 있어

메모리 사용에 효율적이다. 

 

Parcelable 인터페이스 추가 후 class 내부 속성 값에 대해

writeToParcel 및 createFromParcel 등의 메소드를 구현해야한다. 

코틀린을 사용한다면 @Parcelize 어노테이션 추가 및 Parcelable 인터페이스만 추가해주면 되어 편리하다. 

 

java 작성 예시 

class Person implements Parcelable {
    String name;
    int age;
    
    public Person(int age, String name) {
    	this.age = age;
        this.name = name;
    }
    
    public int getAge() {
    	return this.age;
    }
    void setAge(int age) {
    	this.age = age;
    }
    
    public String getName() {
    	return this.name;
    }
    
    void setName(String name) {
    	this.name = name;
    }
    
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(getAge());
        dest.writeString(getName());
    }

    Person(Parcel source) {
        this.age = source.readInt();
        this.name = source.readString();
    }
    
    public static final Parcelable.Creator<Person> = new Creator<Person>() {
    	public Person createFromParcel(Parcel source) {
            return new Person(source);
        }

        public Person[] newArray(int size) {
            return new Person[size];
        }
    }
}

 

kotlin 작성 예시 

@Parcelize
data class Person(
	var name: String, 
	var age: Int
): Parcelable

 

코틀린 만세다. 

 

참고 

https://developer.android.com/reference/android/os/Parcelable

 

 

반응형

'정리하기 > 개발 기본' 카테고리의 다른 글

의존성 주입 (DI)  (0) 2024.01.18
ACL  (0) 2018.08.10
CDN 서버  (0) 2017.12.18
컴파일 vs 빌드  (0) 2017.07.23
숫자 표현 방식  (0) 2017.06.26
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함