[Java] [Android] serializable and inheritance

Source: Internet
Author: User
Tags object serialization

Today, I encountered a problem in my android experiment. It took more than one hour to locate the problem and solve it.

This problem is relatively hidden and will waste a lot of time if you don't know it.

First look at the Code:

In newslistactivity. Java

Intent intent = new Intent(NewsListActivity.this, NewsInfoActivity.class);intent.putExtra("ItemState", item);NewsListActivity.this.startActivity(intent);

In newsinfoactivity. Java

if(intent.getExtras() != null){    item = (RSSItem)intent.getExtras().getSerializable("ItemState");}

The rssitem class must be serializable, that is, implement the serializable interface.

My rssitem inherits the rssobject class, while the rssobject class does not implement the serializable interface.

public class RSSItem extends RSSObject implements Serializable

Now the problem occurs, no compilation error is reported, and no runtime error occurs. However, many attributes of the item obtained by newsinfoactivity are null.

 

Solution: the parent class rssobject must implement the serializable interface.

Http://www.cjsdn.net/post/view? Bid = 2 & id = 192312 & sty = 1 & TPG = 5 & age = 0

1. serialization Overview

Here, I will briefly introduce some concepts related to serialization. If you think you are familiar with serialization, skip this section and take a look at the next section.

Serialization is a very important feature in Java. Through the serialization mechanism, we can convert Java objects into streams, store them in hard disks, or transmit them to other users on the network. Serialization is applied in both RMI and EJB, which is an important technology that constitutes J2EE.

1) serializable Interface

If you want a class to be serializable, the class must implement the serializable interface. This interface does not have any methods and attributes. It serves only to indicate that a class can be serialized, this feature seems to be widely used in Java. For example, cloning uses the same mechanism.

Therefore, if we want to create a class that can be serialized, we can do the same as the following code.

Import java. Io. serializable;

Public class serialclass implements serializable

{

Private Static final long serialversionuid =-190710910746841476l;

Private string C;

Public int;

Public String B;

Public int geta () {return ;}

Public String getb () {return B ;}

Public void Seta (int A) {This. A = ;}

Public void SETB (string B) {This. B = B ;}

Public String GETC () {return C ;}

Public void SETC (string c) {This. C = C ;}

From the above example, we can see that apart from implementing the serialable interface, there is no big difference between a serializable class and a common class. But we still have something special to note.

2) attribute serialversionuid

This attribute is a Private Static final attribute. Generally, people who are new to serialization will ignore this attribute because it is not required. This attribute is mainly used to ensure that a serializable class is in different Java compilers and the same version number can be ensured, this ensures that there is no invalidclassexception exception when this class is serialized or deserialized in different JVMs.

3) attributes and serialization

So let's look at another question: is a class that can be regarded as a serializable class after serializable implementation? The answer is no. In fact, whether a class is serializable depends on its attributes. in Java specifications, whether a class can be serializable depends not only on whether the class implements the serializable interface, it also depends on whether the attributes in this class are serializable. In the preceding example, there are three attributes, two of which are string objects and one of which is an int type attribute. In fact, the string class is serializable (inherits the serializable interface and its attributes are serializable), while basic data types such as int are considered serializable in Java, therefore, we can confirm that the above class is a serializable class. Now we have created a serializable class. The next question is how to use this class for serialization and deserialization?

4) objectoutputstream and objectinputstream

JDK provides two Io stream classes for serialization and deserialization. The writeobject method in objectoutputstream serializes an object, while the readobject method in objectinputstrem is responsible for serialization. The following example shows the serialization and deserialization of a class.

Package serialtest;

Import java. Io. fileinputstream;

Import java. Io. fileoutputstream;

Import java. Io. objectinputstream;

Import java. Io. objectoutputstream;

Public class testclass

{

Public static void main (string [] ARGs) throws exception

{

Serialclass S = new serialclass ();

S. Seta (10 );

S. SETB ("hello ");

S. SETC ("world ");

// Create an objectoutputstream object and prepare the serialized object s

Objectoutputstream OOS = new objectoutputstream (

New fileoutputstream ("ABC "));

// Call writeobject to serialize the object and store it in the object ABC.

Oos. writeobject;

Oos. Flush ();

Oos. Close ();

// Create an objectinputstream object and prepare to deserialize the serialclass object from the object ABC

Objectinputstream OIS = new objectinputstream (

New fileinputstream ("ABC "));

// Call readobject to deserialize the byte stream stored in the object ABC to a serialclass object.

S = (serialclass) Ois. readobject ();

System. Out. println (S. Geta ());

System. Out. println (S. getb ());

System. Out. println (S. GETC ());

}

}

Execute the program. The final result should be:

10

Hello

World

Well, the basic serialization knowledge is here. Next we will look at the impact of inheritance on serialization.

Ii. Impact of inheritance on serialization

Now we convert the above example into the following form.

1) first create an interface.

Package serialtest;

Public interface superinterface

{

Public int geta ();

Public String getb ();

Public void Seta (int );

Public void SETB (string B );

}

2) create an abstract class to implement the superinterface interface. Note that this class does not implement the serializable interface.

Package serialtest;

Public abstract class abssuperclass implements superinterface

{

Public int;

Public String B;

Public int geta () {return ;}

Public String getb () {return B ;}

Public void Seta (int A) {This. A = ;}

Public void SETB (string B) {This. B = B ;}

}

3) The serialclass inherits absuperclass and implements the serializable interface.

Package serialtest;

Import java. Io. serializable;

Public class serialclass extends abssuperclass implements serializable

{

Private Static final long serialversionuid =-190710910746841476l;

Private string C;

Public String GETC () {return C ;}

Public void SETC (string c) {This. C = C ;}

}

At this time, we are running test and we will find that the results are different from the first example. At this time, the results will become:

0

Null

World

The cause of this result is absuperclass. Because absuperclass does not implement the serializable interface, it cannot be serialized. However, because serialclass implements the serializable interface, it becomes a serializable class, at this time, because attribute C is a serialclass class, the value of C will be saved during serialization, and attributes A and B are inherited from absuperclass, because of absuperclass, their values cannot be saved in serialization.

I have also confirmed this in the Java documentation. In Java Doc, it is clearly stated that if a class inherits a non-serializable class, if you want to save the attributes of the parent class in serialization, You need to implement additional code to explicitly store the attribute values of the parent class.

Finally, I will go back to the original intention of this article. It is true that this article focuses on Object serialization, but at last I will go back to a relatively old topic, that is, during software development, to what extent should inheritance be used? After all, misuse of inheritance will have a profound impact on the entire system.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.