My class is serializing w/o implementing serializable

I have a class Foo that implements Serializable.
Foo has a data member that is an instance of class Bar.
Class Bar does NOT implement Serializable.
When I serialize an instance of Foo out to a file and
then deserialize it back in, I'm seeing Bar's no-arg
constructor being called.
Shouldn't I be getting IOExceptions on the write and
and read of my Foo instance when the JVM tries to
write/read the Bar member, since only classes that implement
Serializable can be serialized/deserialized?
Oh, I'm using JDK 2SDK version 1.3.1
-Steve

From the Serializable API
"To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable in this case. The error will be detected at runtime."
There seems to be a mistake in the second to last sentence. I would think itr should say 'It is an error to declare a class Serializable if this is not the case'.

Similar Messages

  • Using a class or servlet that implements Serializable

    Hello everyone,
    Can someone please help me. I need to make a program that uses a class or servlet that implements Serializable and then use the values of the variables in servlets.
    The first is using it to validate login. then changing the color of the background, header and footer of each servlet.
    the variables in the Serialized file are all Strings for color, username, password, header text and footer text.
    I tried using the applet tag to run the class in the servlet but it is not working.

    It's not working because you seem to be making random guesses what servlets, serialization and files are

  • Problem with NotSerializableException on class implementing Serializable

    Hi,
    Any idea as to why I get this exception, and what I can do to avoid it ?
    java.io.NotSerializableException: util.NumberStore$UserI have this, relatively simple, class
    class User implements Serializable
         private static long serialVersionUID = 1L;
         private String uid;
         private String nr;
         public User(){}
         public User( String uid, String nr ) {
              this.uid = uid;
              this.nr = nr;
         public String getUid()     {
              return uid;
         public String getNr() {
              return nr;
         public void setUid(String uid){
              this.uid = uid;
         public void setNr(String nr){
              this.nr = nr;
    }When loading and saving it, I use these two methods:
         private void saveLocalList()
              FileOutputStream f = null;
              try {
                   f = new FileOutputStream("./users.dat");
                   ObjectOutputStream out = new ObjectOutputStream(f);
                   for (User u: numbers)
                        out.writeObject(u);
                   f.close();
              } catch (IOException e) {
                   System.err.println("User info not saved:"+e.getLocalizedMessage());
                   if (f != null)
                        try {
                             f.close();
                        } catch (IOException e1) {
         private boolean loadLocalList()
              FileInputStream f = null;
              try {
                   f = new FileInputStream("./users.dat");
                   ObjectInputStream input = new ObjectInputStream(f);
                   numbers = new ArrayList<User>();
                   User u = (User) input.readObject();
                   while (u != null)
                        numbers.add(u);
                        u = (User) input.readObject();
                   f.close();
                   return true;
              } catch (FileNotFoundException e) {
                   return false;
              } catch (IOException e) {
                   e.printStackTrace();
                   if (f != null)
                        try {
                             f.close();
                        } catch (IOException e1) {
                             // ignore close errors
                   return false;
              } catch (ClassNotFoundException e) {
                   if (f != null)
                        try {
                             f.close();
                        } catch (IOException e1) {
                             // ignore close errors
                   return false;
         }Both the User class and the methods are found within the NumberStore class.

    The User class indeed does not contain any references at all to the NumberStore classIf 'User' is nested inside 'NumberStore' and it isn't static, User does indeed have a hidden reference to the outer class NumberStore. That's how the syntax 'NumberStore.this' works.
    I can say with absolute certainty that an object which was not marked as serializable was written to the users.dat file.Quite apart from the fact that the source code of ObjectOutputStream makes it utterly impossible, I don't see how you can possibly say that 'with absolute certainty'. For a start there's no information in the file to indicate what interfaces were and weren't implemented by the class of the serialized object at the time it was serialized.
    I'm not absolutely positive about whether or not it bombed out on this occassion, or when trying to re-read it next time aroundNotSerializableException is only thrown when writing, not when reading, so that answers that.
    Do you still have the file? I'd like to see exactly what was written. In any case a serialization file that copped any kind of IOException when being written should have been thrown away immediately, you're right about that.
    BTW your reading code is wrong. You shouldn't be testing for null, unless you are deliberately writing a null as a sentinel value. You should be catching EOFException.

  • Example class that implements Serializable interface

    Dear,
    I have a class myData that I want to implement Serializable interface. class myData has only two fields: Integer iData1, String sData2.
    Could anybody shown me how my myData class should be?
    Thanks a lot!

    Hey, if you have yet to obtain a remote reference from the app server ...then we are into pandora's box. I lost three whole heads of hair getting up on JBoss when I first started. You want to check out the JBoss forums on the JBoss website, and the enterprise javabeans forum here. Search some posts and read the free JBoss manual.
    Unfortunately, there isn't a 'here, do this' solution to getting connected with JBoss. There are quite a few gotcha's. There are descriptors, descriptor syntax ...and this changes between releases so there seems to be alot of people saying 'here, do this' ...but you try and it doesn't work (wrong release). Here are some descriptors that I threw up recently for someone ...a place to start.
    http://forum.java.sun.com/thread.jsp?forum=13&thread=414432
    This drove me nuts until it all worked right. I was stuck for three weeks at one point ...ready to give up, but then I got it. Perservere ...its a nice container for learning in (its free!).
    I will try and watch for you.
    Oh, and put something in your head ...at least then you will keep your hair !
    :)

  • Drawbacks in implementing Serializable

    Hi All,
    On my current project I have to serialize a big objects tree. This means that all the non transient objects referenced by the main object must implement Serializable. Since the referenced classes are part of a library used also for other purposes, I was wandering if there is any drawback in implementing broadely Serializable (performance, class size ???).
    Any though is really appreciated.
    Thanks in advance,
    Stefano

    AFAIK, just saying that your class implements java.io.Serializable does not make it perform badly. Serializable is just a "tag" to identify your class as a Serializable class. It does not "automatically" add any overhead or deteriorate its performance.
    When a class which is Serializable is actually serialized ... all the above performance issues come to play.
    Hope that is what you were enquiring about ...
    --Das                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • If a class is serialized,will its innerclass gets automatically serialized?

    There is a Class,which is Serialized...i have declared an innerclass which has not implemented Serializable interface...will that innerclass gets serialized Or not..??'
    Regs
    Sudhy...

    The answer you gave boils down to "if
    an object is serializable it will be serialized,
    otherwise it won't."Not at all, it boils down to 'if the object is reachable from a serialized object it will be serialized otherwise not', with the appropriate qualifications.
    Your response oversimplified the
    possibilities - not taking into account that if the
    inner class doesn't create any objects and only
    manipulates serializable fields of the outer class
    then they will participate in the serialization, or
    that the inner class objects will be serializable if
    it's a subclass of the outer class, as examples..I don't understand any of this. Inner classes are not serialized at all[i/], it is [i]instances which may or may not be serialized, and this only depends on whether they are directly or indirectly reachable from the outer class instance, and not in the least on what the inner class does or doesn't do with fields of the outer class or whether it has field objects of its own.
    I agree that an inner class which extends a serializable outer class will be serialiable, but that wasn't the question.
    BTW reachability is not discussed in the article cited at all and neither is your other misconception quoted above.

  • Why we require to implement Serializable interface?

    Hi techies,
    I am new to Serialization. Why we require to use Serializable interface for Serializing objects. Since Serializable interface is a marker interface, how it prevents objects not implementing Serializable from being Serialized. Does Java Compiler checks it or how it checks it?

    JavaBreather wrote:
    Since Serializable interface is a marker interface, how it prevents objects not implementing Serializable from being >Serialized. Does Java Compiler checks it or how it checks it?Compiler does nothing but mark the class as implementing the interface. You can then later check whether “objects instanceof Interface" and find out whether or not it is present. As said above, ObjectOutputStream does the same thing.
    Marker interfaces are a misuse of interfaces, and should be avoided. You shouldn't create new ones.Annotations introduce in Java 5 are a generic mechanism of adding metadata to a class.

  • Vector does NOT implement Serializable

    Hi :
    can anyone think of a reason why Vector does not implement Serializable?
    Suppose, I want to send a Vector of TimingResults accross a dataStream,
    now TimingResult is a class that I created which does implement Serializable, yet I am getting erroneus results everytime ....

    according to the 1.4.1 docs, Vector does implement the
    Serializable interface.You are absolutely right...
    sorry guys...my brain is fried this afternoon...

  • If I remove "implements serializable" XMLEncoder/decoder still works ???

    Like the title says, if I remove "implements serializable" from the class declaration, I can still write out the file to XML. Why?
    Also, I'm using hungarian notation instead of following the normal javabean naming convention. Shouldn't this break the XMLEncoding/decoding process ??
    For example, in my class I have a few variables:
    private int iAge = 1;
    private String szName = "John Smith";
    public void setAge( int iNewAge ) {
            iAge = iNewAge;
    public void setName( String szNewName ) {
            szName = szNewName;
    }When it's written to XML, it uses "name" instead of "szName". How does it know that setName refers to the variable szName (instead of some variable called "name" which does not exist?
    <void property="name">
       <string>Name here</string>
    </void>Thanks

    When it's written to XML, it uses "name" instead of
    "szName". How does it know that setName refers to
    o the variable szName (instead of some variable
    called "name" which does not exist?It doesn't know anything about the variable. JavaBeans will, by default, look at getter and setter methods. Since you have setName and setAge, and no BeanInfo (I think that's the name) class to say otherwise, the result is that in JavaBeans world, you have a name and an age property, and they're accessed through those methods.

  • [svn:bz-trunk] 22429: Adding the default fallback of serializer and deserializer classes to amf deserializer and amf serializer

    Revision: 22429
    Revision: 22429
    Author:   [email protected]
    Date:     2011-09-07 08:04:46 -0700 (Wed, 07 Sep 2011)
    Log Message:
    Adding the default fallback of serializer and deserializer classes to amf deserializer and amf serializer
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/io/SerializationContext.java

  • Class parametrized type extends and implements, possible?

    Hi all,
    Maybe I'm not understanding it well, but every time I try to use generics for something useful I get to a point in which I need to define something like this:
    public interface MyInterface<T> {
    public T get();
    public void set(T var);
    public class MyClass<T extends Component & MyInterface<T2> > {
    T myObject;
    .... somewhere in the code:
    T2 value;
    value = myObject.get();
    To me, this would be very useful, but MyClass does not compile. I hope what I try to do is clear (I want T to be a sub class of Component that also implements a parametrized interface). I don't know what I'm doing wrong nor if this is even possible. Believe me when I say I have done a lot of research (and people thought C++ templates where complicated...).
    My main problem is having a parametrized type that contains a parametrized type and trying to have both types' parameters available for use in the class.
    Any ideas?

    This compiles in beta2:
    public class MyClass<T2, T extends Component & MyInterface<T2> > {
       T myObject = null;
      void x() {
          myObject.bar();
          T2 a = myObject.get();
    interface MyInterface<T> {
          T get();
          void set(T var);
    class Component {
        public void bar() {}
    }but removing the public modifier from Component.bar() will give the error: cannot find symbol.

  • Anonymous class instantiation expression with interface implementation??

    Is it possible to create an inline anonymous class instatiation expression that can implements an interface?
    For example:
    Frame myFrame = new Frame() implements WindowListner {
         public void WindowOpened(WindowEvent  e) {}
             +other interface methods....+
    }Apparently compiler doesn't like this code:(
    I know that I can create an extra named class with the interface, then instantiate it instead. But this is not what I want.
    (By the way, if someone wants to know why I want to do this, I say I think this may make my code simpler or look better, that's all:) )

    abstract class ListenerFrame extends Frame implements WindowListener {} This look pretty neat:)
    I guess I can rewrite my code then:
    abstract class FrameWithListener extends Frame
             implements WindowListener{}      //local class
    Frame myFrame = new FrameWithListener {
            public void WindowOpened {}
               blah, blah...
    }Not sure I can use abstarct class as local class, but otherwise I'll use it as a class member or some sort..
    Thank you for the reply
    Edited by: JavaToTavaL on Nov 27, 2009 4:04 AM
    Edited by: JavaToTavaL on Nov 27, 2009 4:04 AM

  • Modifying a Class that implements Serializable

    I have a class LDAPUser
    import java.io.*;
    public class LDAPUser implements java.io.Serializable{
         private java.lang.String name;
         private java.lang.String userID;
         private java.lang.String associateNumber;
    public LDAPUser() {
         super();
    public boolean equals(Object o) {
         if (o == this)
         return true;
         if (!(o instanceof LDAPUser))
         return false;
         return (((LDAPUser)o).getAssociateNumber().equals(this.getAssociateNumber()));
    public java.lang.String getAssociateNumber() {
         if(associateNumber == null){
              return getUserID();
         return associateNumber;
    public java.lang.String getName() {
         return name;
    public java.lang.String getUserID() {
         return userID;
    public void setAssociateNumber(java.lang.String newAssociateNumber) {
         associateNumber = newAssociateNumber;
    public void setName(java.lang.String newName) {
         name = newName;
    public void setUserID(java.lang.String newUserID) {
         userID = newUserID;
    It works fine.
    I needed to add functionality to it. These were the modifications.
    private java.lang.String distinguishedName;
    private boolean validUser;
    public java.lang.String getDistinguishedName() {
         return distinguishedName;
    public boolean isValidUser() {
         return validUser;
    public void setDistinguishedName(java.lang.String newDistinguishedName) {
         distinguishedName = newDistinguishedName;
    public void setValidUser(boolean newValidUser) {
         validUser = newValidUser;
    I am using visual age for java and in the Test environment the changes work fine.
    When I promote the changes to our application server (websphere) the changes are not there. I get a method not found error and though trial and error have identified that the server is not actually using the class from the jar. I have removed any other occurences of the class from the server.
    My question is if I change a Serializable class how do I make those changes take affect (thorough better coding) and for right now, where is this "old instance" of my class coming from and how do I get rid of it.
    Thanks in Advance,
    Jason Grieve

    If the server is running than the class might be already loaded through the class loader, so it wont be load again.
    this unless you use hot deployment, which you have to figure how it is being handled in your srver.
    Doron

  • Parallel to serial conversion for implementing FSK modulation on fpga

    I want to implement FSK modulation in LABview FPGA using the arithematic VIs. My bit rate is 625 kbps and sampling rate of the waveforms i utilize is 80 MHz.(for 0 i use 1.25 MHz and for 1 2.5 MHz). I want to take AUDIO input from computer and modulate it and then transmitting it into the air. Modulation has to be done in FPGA Vi. Now i want to convert the sample values coming at particular rate to bits (parallel to serial conversion) representing the samples these bits should come one by one at the rate of 625 kbps to select vi which would select the waveform depending on zero or one on its select port. I want to know how parallel to serial conversion can be done in labview
    KAMRAN ZIA
    UNGERGRADUATE STUDENT (AVIONICS)

    Hi Kamran,
    With respect to the first issue, it should be relatively straightforward to generate the signal you want. In your FPGA code, I would assume that you have a sine wave generator. In the configuration screen, you can elect to show the frequency terminal. you can generate a certain amount of data (whatever you require) and then when the FPGA loops again, generate the next section of waveform based on the bit you want to output.
    a few documents on our website include:
    http://zone.ni.com/devzone/cda/tut/p/id/3253
    http://decibel.ni.com/content/docs/DOC-5412
    http://forums.ni.com/t5/Real-Time-Measurement-and/Simple-FSK-signal-generation/m-p/783361?requireLog...
    With respect to the second issue, there are many many ways to do it. I have attached a very basic example which shows you one such option. It takes a U8 (a single byte) and spits out each of the contained bits at 40 MHz.
    Thanks,
    D Smith
    Attachments:
    parallel to serial FPGA.vi ‏26 KB

  • Why does this abstract class and method work without implement it?

    hi,
    I have seen many times that in some examples that there are objects made from abstract classes directly. However, in all books, manual and tutorials that I've read explain that we MUST implement those methods in a subclass.
    An example of what I'm saying is the example code here . In a few words that example makes Channels (java.nio.channel) and does operations with them. My problem is in the class to make this channels, because they used the ServerSockeChannel class and socket() method directly despite they are abstracts.
       // Create a new channel: if port == 0, FileChannel on /dev/tty, else
       // a SocketChannel from the first accept on the given port number
    private static ByteChannel newChannel (int netPort)
          throws Exception
          if (netPort == 0) {
             FileInputStream fis = new FileInputStream ("/dev/tty");
             return (fis.getChannel());
          } else {
    //CONFLICT LINES
             ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
             ssc.socket().bind (new InetSocketAddress (netPort)); //<--but here, this method (socket) is abstract. WHY RETURN A SOCKET????????  this mehod should be empty by default.
             System.out.print ("Waiting for connection on port "
                + netPort + "...");
             System.out.flush();
             ByteChannel channel = ssc.accept();
             ssc.close();
             System.out.println ("Got it");
             return (channel);
       } I test this code and works fine. So why can it be??
    Also, I read that the abstract classes can't have static methods. Is it true???
    Please Help!!
    PS: i have seen this kind of code many times. So i feel that I don't understand how its really the abstract methods are made.
    PS2: I understand that obviously you don't do something like this: *"obj = new AbstractClass(); "*. I dont understand how it could be: ServerSocketChannel ssc = ServerSocketChannel.open(); and the compiler didn't warn.

    molavec wrote:
    ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
    The static method creates an instance of a class which extends ServerSocketChannel, but is actually another non-abstract class.I thought that, but reading the documentation I saw that about open() method:
    Opens a server-socket channel.
    The new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object.
    The new channel's socket is initially unbound; it must be bound to a specific address via one of its socket's bind methods before connections can be accepted.
    ...and the problem is the same openServerSocketChannel is abstract, so i don't understand how it could return a ServerSocketChannel.There is a concrete implementation class that has implemented that method.
    I guess that really the open() method use a SelectorProvider's subclase but it doesn't appear in the doc.It doesn't need to. First, you don't care about those implementation details, and second, you know that if the class is abstract, it must use some concrete subclass.
    Ok, I speak Spanish by default (<-- this sounds like "I am a machine", ^_^' ). So, I didn't know how to say that the method would be {}. Is there a way to say that?? I recommendable for me to know, for the future questions o answers.Not sure what you're saying here. But the other respondent was trying to explain to you the difference between an abstract method and an empty method.
    // abstract method
    public abstract void foo();
    // empty method
    public void bar() {
    Which class does extend ServerSocketChannel? I can not see it.It may be a package-private class or a private nested class. There's no need to document that specific implementation, since you never need to use it directly.

Maybe you are looking for