Solved

A Serialization Question

Posted on 2001-06-20
8
281 Views
Last Modified: 2011-09-20
Experts,

I have a class named Address which has NOT implemented the Serializable interface. Then I have another class Employee which has implemented the Serializable interface. This Employee class HAS-A Address object embedded as a data member. I do the serialization. I can see the file employee1.dat is created but no data. Why the serialization is not happenning?. Here is the sample program.

prain.


import java.io.*;

class Address
{
     private String address;

     public Address(){}

     public Address( String a )
     {
          setAddress( a );
     }

     public void setAddress( String a )
     {
          address = a ;
     }

     public String getAddress()
     {
          return address;
     }

     public String toString()
     {
          return address;
     }
}

class Employee implements Serializable
{
     String name;
     Address addr;

     public Employee( String a, String b )
     {
          name = a;
          addr = new Address( b );
     }

     public String toString()
     {
          return "Employee: " + name + addr.toString();
     }

     private void writeObject( ObjectOutputStream objout ) throws IOException
     {
          try
          {
               objout.writeObject( addr.getAddress() );
               objout.defaultWriteObject();
          }

          catch( Throwable ex ){}
     }

     private void readObject( ObjectInputStream objin ) throws IOException
     {
          try
          {
               addr.setAddress( (String)objin.readObject() );
               objin.defaultReadObject();
          }

          catch( Throwable ex ){}
     }

     public static void main( String[] args )
     {
          Employee emp = new Employee( "Jack", "Bay Area" );

          try
          {
               ObjectOutputStream out = new ObjectOutputStream( new
BufferedOutputStream( new FileOutputStream( "employee.dat" )));
               out.writeObject( emp );

               out.close();

          }

          catch( Exception e ){}

          try
          {
               ObjectInputStream in = new ObjectInputStream( new
BufferedInputStream( new FileInputStream( "employee.dat" )));

               Employee emp1 = (Employee)in.readObject();
               System.out.println( emp1 );

          }

          catch( Exception e ){}

     }
}



0
Comment
Question by:prain
8 Comments
 
LVL 3

Accepted Solution

by:
rjackman earned 50 total points
ID: 6210346
hi
The reason is u can't serailise the object which does not implements the Serializable interface
u are getting the exception here but since u have nothing in cath u are not able to c the exception
pls try following
try
{
//ur code goes here
}
catch(Exception ee)
{
  ee.printStackTrace();
}

Soln to the problem is Address shold implement the Serializable interface,
cheers
RJ
0
 
LVL 9

Assisted Solution

by:Ovi
Ovi earned 50 total points
ID: 6210419
Here is an simple example of mine which save the state of an JFrame :


import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class Serialization extends JFrame {
     protected String title;
     protected Dimension size;
     protected transient JButton sizer = new JButton("HalfSize");
     protected transient JButton titler = new JButton("Title reducer");    
     
     public Serialization(String t, Dimension d) {
          if(!loadState()) {
               setTitle(t);
               setSize(d);              
          }
         
          sizer.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    Serialization.this.setSize(new Dimension(size.width/2, size.height/2));
               }
          });
          titler.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    Serialization.this.setTitle(title.substring(0, title.length() - 1));
               }
          });
          getContentPane().setLayout(new BorderLayout());
          getContentPane().add(sizer, BorderLayout.NORTH);
          getContentPane().add(titler, BorderLayout.SOUTH);
          addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent w) {
                    saveState();
                    System.exit(0);
               }
          });
     }
     
     public void setTitle(String t) {
          title = t;
          super.setTitle(t);
     }
     
     public String getTitle() {
          return(title);
     }
     
     public void setSize(Dimension d) {
          size = d;
          super.setSize(d);
     }
     
     public Dimension getSize() {
          return(size);
     }
     
     private void saveState() {
         try {
           FileOutputStream fos = new FileOutputStream ("obj.ser");
           ObjectOutputStream oos = new ObjectOutputStream (fos);
           oos.writeObject (this);
           oos.flush();
           oos.close();
           System.out.println("Saved to disk");
         } catch (IOException e) {
           System.out.println("Unable to save");
           e.printStackTrace();
         }          
     }
     
     private boolean loadState() {
          try {
               FileInputStream fis = new FileInputStream("obj.ser");
               ObjectInputStream ois = new ObjectInputStream(fis);
               Object o = ois.readObject();
               ois.close();
               if(o != null)  {
                    setSize(((Serialization) o).getSize());
                    setTitle(((Serialization) o).getTitle());
                    return(true);
               }
          } catch(FileNotFoundException e1) {
               System.out.println("Nu exista fisierul");
          } catch(IOException e2) {
               System.out.println("IOException...");
          } catch(ClassNotFoundException e3) {
               System.out.println("Nu gasesc clasa ");
          }
          return(false);
     }    

     public static void main(String args[]) {
          Serialization s = new Serialization("Serialization example", new Dimension(600, 600));
          s.setLocation(200, 200);
          s.setVisible(true);
     }    
}
0
 
LVL 3

Expert Comment

by:superschlonz
ID: 6210434
There are several bugs in class Emplyeee:

1. make the fields transient which should not be serialized:

transient Address addr;

2. call defaultWriteObject() and defaultReadObject() before writing/reading
other data.

3. In readObject) method the address is null when you want to call setAddress(),
you have to allocate a new object.

addr = new Address( (String)objin.readObject() );

4. why do you make this tray {} catch( Throwable 9 {} without doing something when
it fails. This way you won't find out that something failed reading or writing.
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6210490
My code is not supposed to be a Java bean, but if your read the specification of the Java Bean components there are some restrictions for working with the default serialization process like :
in order to be serializable an java Bean must provide :
- implements Serializable or Externalizable (this only if you implement yourself the serialization) interfaces
- an default constructor which takes no parameters.
- pairs of methods getFoo...&setFoo... for the serializable fields;
- static and final members are not serializable;
- all nonserializable fields must be declared as transient.
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 9

Expert Comment

by:Ovi
ID: 6210496
My code is not supposed to be a Java bean, but if your read the specification of the Java Bean components there are some restrictions for working with the default serialization process like :
in order to be serializable an java Bean must provide :
- implements Serializable or Externalizable (this only if you implement yourself the serialization) interfaces
- an default constructor which takes no parameters.
- pairs of methods getFoo...&setFoo... for the serializable fields;
- static and final members are not serializable;
- all nonserializable fields must be declared as transient.
0
 

Expert Comment

by:Tuvok
ID: 6828809
This question appears to have been abandoned. In fact, I will include links to ALL your open questions

below:

Your options are:
1.  Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you. You must tell the participants why you

wish to do this, and allow for Expert response.
3.  Ask Community Support to help split points between participating experts, or just comment here with

details and we'll respond with the process.
4.  Delete the question. Again, you must tell the other participants why you wish to do this.

For special handling needs, please post a zero point question in the link below, include the question

QID/link.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt

Please click this Help Desk link for Member Guidelines, Member Agreement and the Question/Answer process:

Click you Member Profile to view your question history and keep them all current with updates as the

collaboration effort continues.
http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp


PLEASE DO NOT AWARD THE POINTS TO ME.  

------------>  EXPERTS:

Please leave any comments regarding this question here on closing recommendations if this item remains

inactive another three days.

Thank you everyone.

Open Qs:
http://www.experts-exchange.com/jsp/qShow.jsp?qid=11862698
http://www.experts-exchange.com/jsp/qShow.jsp?qid=11874078
http://www.experts-exchange.com/jsp/qShow.jsp?qid=20059847
http://www.experts-exchange.com/jsp/qShow.jsp?qid=20138628
http://www.experts-exchange.com/jsp/qShow.jsp?qid=20158216
http://www.experts-exchange.com/jsp/qShow.jsp?qid=20158215
http://www.experts-exchange.com/jsp/qShow.jsp?qid=20167637
http://www.experts-exchange.com/jsp/qShow.jsp?qid=20167641
http://www.experts-exchange.com/jsp/qShow.jsp?qid=20270929


Tuvok
Moderator @ Experts Exchange

P.S.  For year 2000 question, special attention is needed to ensure the first correct response is awarded,

since they are not in the comment date order, but rather in Member ID order.

0
 

Expert Comment

by:CleanupPing
ID: 9062034
prain:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 9253853
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:


[points to Ovi]


Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
sudhakar_koundinya
EE Cleanup Volunteer
---------------------
If you feel that your question was not properly addressed, or that none of the comments received were appropriate answers, please post your concern in THIS thread.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
The viewer will learn how to implement Singleton Design Pattern in Java.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now