2012-03-28 4 views
10

지금까지 나는 Parcelable 개체를 문제없이 살펴 보았습니다. 주로 모든 구성원의 메서드가 writeX() 개의 메서드와 연결되어 있기 때문에 문제가 없습니다.개체를 소포로 작성

public String name; 

private Foo(final Parcel in) { 
    name = in.readString(); } 
public void writeToParcel(final Parcel dest, final int flags) { 
    dest.writeString(name); } 

하지만 지금은 Bar 회원 일들이 나를 위해 조금 위험한를 얻을 수있는 경우 : 예를 들어, 내가 할

public Bar bar; 

private Foo(final Parcel in) { 
    bar = new Bar(); //or i could actually write some constructor for Bar, this is a demo. 
    bar.memberString = in.readString(); 
} 

public void writeToParcel(final Parcel dest, final int flags) { 
    // What do I do here? 
} 

난이 잘못된 방향으로 접근하는 건가요? 소화물 구성원 Bar s에 내 writeToParcel에서 무엇을해야합니까?

답변

25

정확하고 더 많은 OO 방식은 Bar가 Parcelable도 구현합니다.

는 개인 푸 생성자에서 줄을 읽으려면 :
private Foo(final Parcel in) { 
    ... ... 
    bar = in.readParcelable(getClass().getClassLoader()); 
    ... ... 
} 

은 writeToParcel 방법에 줄을 작성하려면이 도움이

public void writeToParcel(final Parcel dest, final int flags) { 
    ... ... 
    dest.writeParcelable(bar, flags); 
    ... ... 
} 

희망을.

+2

일부는 여기에 혼란을 얻을 수 있기 때문에 ** getClass(). getClassLoader를가() ** 의미 추가 ** Bar.class.getClassLoader() ** – Juni

+0

내 클래스가 SDK에 의해 제공되며 수정할 수없는 경우 어떻게해야합니까 무엇 ? – Eido95

0

Parceables는 통증이며 참조가 아닌 값으로 전달됩니다. 나는 그 (것)들을 사용하여 결코 추천하지 않을 것입니다. 응용 프로그램의 경우 정적 모델 인스턴스를 만들고 필요한 객체에 shim 참조 만 가져옵니다.

+0

현자의 단어 –

+0

싱글 톤을 디자인 원리로 사용하는 것은 객체 지향 프로그래밍에 결함이 있습니다. json으로 deserialize하거나 값을 저장하고, 다른 모든 클래스가 액세스 할 수있는 전역 클래스가 없는지 확인하십시오. – HarshMarshmallow