ObjectInputStream.GetFields: Useful in readObject()?

The following is an excerpt from the User Guide description of ObjectInputStream.GetField class (http://java.sun.com/j2se/1.3/docs/guide/serialization/spec/input.doc2.html):
��Using readFields to access the serializable fields does not change the format of the stream. It only provides an alternate API to access the values which does not require the class to have the corresponding non-transient and non-static fields for each named serializable field. The serializable fields are those declared using serialPersistentFields or if it is not declared the non-transient and non-static fields of the object. When the stream is read the available serializable fields are those written to the stream when the object was serialized. If the class that wrote the stream is a different version not all fields will correspond to the serializable fields of the current class. The available fields can be retrieved from the ObjectStreamClass of the GetField object.�
Based on this description, I assumed that this API could be used within an object�s readObject() method to retrieve fields with names/types that differ from the current object. This assumption appears to be false.
In my tests with 1.3 and 1.4.01, the serialization code makes a number of comparisons between the class being deserialized, and the local (vm loaded) version of the class. These comparisons include class cast compatibility, serialVersionUID compatibility, and field name/type compatibility. If any of the test fail, an appropriate exception is thrown. These tests are performed before the call is made to the object�s readObject method. (In 1.4_01, these tests are performed by ObjectSteamClass.initNonProxy().)
In the following example, Foo (version 2) cannot successfully deserialized Foo (version 1). The serialization mechanism with throw a field type mismatch on �field1� before calling readObject(). Foo (version 2b) will fail as well. This time, because of an incompatible serialVersionUID.
// Version 1
public class Foo implements Serializable
    private static final long serialVersionUID = 1L;
    protected int field1 = 123;
// Version 2
public class Foo implements Serializable
    private static final long serialVersionUID = 1L;
    protected String field1 = 123;
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
        ObjectInputStream.GetField fields = in.readFields();
        field1 = Integer.toString(fields.get(�field1�,  0));
// Version 2b
public class Foo implements Serializable
    private static final long serialVersionUID = 2L;
    protected String field1 = 123;
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
        ObjectInputStream.GetField fields = in.readFields();
        field1 = Integer.toString(fields.get(�field1�,  0));
}It appears ObjectInputStream.readFields() cannot be used within readObject() as the documentation describes. Am I missing something?
Thanks, Craig.

Oops. In version 2 and 2b, the following line:
protected String field1 = 123;should read:
protected String field1 = "123";

Similar Messages

  • How could I create ObjectInputStream and use it indefinitely with Servlets?

    Hi All,
    I would like to create the stream object between applet and server only once with urlConnection.openConnection() and use it to write objects to it indefinitely without reinstantiating it or getting another connection with urlConnection.openConnection() and repeatedly query for another input / output stream with servletOutputStream = new ObjectOutputStream (servletLinkup.getOutputStream()); How could this be done?
    Devyn

    Dear vladimp,
    The thing is, you need to ask good questions to receive good answers.Have you ever written a servlet vladimp? More specifically, have you ever written client - server code and have the two sides send objects to each other over the HTTP protocol?
    This question is directed towards those developers who have done similar code and may have suggestions regarding this post.
    What have you tried and how exactly has it failed for you?Quote from my post: "I would like to create the stream object between applet and server only once with urlConnection.openConnection() and use it to write objects to it indefinitely without reinstantiating it or getting another connection..." - that is, every time I want to write another object to the stream. Apparently whatever I tried didn't work, hence I'm posting here. Maybe someone with more servlet development experience would be willing to shed some light on this.
    Why do you think the overhead of wrapping ObjectInput/OutputStreams
    around the URL stream is large?Why do you believe I care if the overhead is large? My question is about maintaining a persistent connection to a servlet not overhead.
    Have you made use of OutputObjectStream.reset()?This is actually a legitimate question (even though it's an ObjectOutputStream not a OutputObjectStream). The answer is YES I tried and NO it didnt' work. Could be that anything sent has to be followed up by a .flush() or/and a .close() to actually trigger the stream to send the object. At least according to some sources (I'm trying to verify this).
    How about some sample code that reproduces the issue?URLConnection servletLinkup = urlConnection.openConnection();
    servletOutputStream = new ObjectOutputStream (servletLinkup.getOutputStream());
    Should be obvious for someone who did it before.
    What is it about this problem that warrants a post to Advanced
    Language Topics forum vs, say, Serialization forum?Testosterone driven guru java developers. Perhaps this could also go under the 'Java Servlet Technology' section as well, who knows, there's so many to choose from. I've actually gotten some very creative replies regarding this in other places. I can't say I didn't enjoy this post, however. 8^D. Thnx to all who have read the post.
    Devyn

  • Tuning the performance of ObjectInputStream.readObject()

    I'm using JWorks, which roughly corresponds to jdk1.1.8, on my client (VxWorks) and jdk1.4.2 on the server side (Windows, Tomcat).
    I'm serializing a big vector and compressing it using GZipOutputStream on the server side and doing the reverse on the client side to recreate the objects.
    Server side:
    Vector v = new Vector(50000);//also filled with 50k different MyObject instances
    ObjectOutputStream oos = new ObjectOutputStream(new GZipOutputStream(socket.getOutputStream()));
    oos.writeObject(v);Client side:
    ObjectInputStream ois = new ObjectInputStream(new GZipInputStream(socket.getInputStream()));
    Vector v = (Vector)ois.readObject();ObjectInputStream.readObject() at the client takes a long time (50secs) to complete, which is understandable as the client is a PIII-700MHz and the uncompressed vector is around 10MB. Now the problem is that because my Java thread runs with real time priority (which is the default on Vxworks) and deprive other threads, including non-Java ones, for this whole 50 sec period. This causes a watchdog thread to reset the system. I guess most of this delay is in GZipInputStream, as part of the un-gzipping process.
    My question is, is there a way to make ObjectInputStream.readObject() or any of the other connected streams (gzip and socket) yield the CPU to other threads once in a while? Or is there any other way to deal with the situation?
    Is the following a good solution?
    class MyGZipInputStream extends GZipInputStream {
        public int count = 0;
        public int read(byte b[], int off, int len) throws IOException {
             if(++count %10 == 0) // to avoid too many yields
                  Thread.yield();
              return super.read(b, off,len);
    }Thanks
    --kannan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I'd be inclined to put the yielding input stream as close to the incoming data as possible - thus avoiding any risk that time taken to read in data and buffer it will cause the watchdog to trip.I could do that. But as I'm doing Thread.yield only once every x times, would it help much?
    Also, as I've now found out, Thread.yield() wouldn't give other low priority tasks a chance to run. So I've switched to Thread.sleep(100) now, even though it could mean a performance hit.
    Another relaed question - MyGzipStream.read(byte[], int, int) is called about 3million times during the readObject() of my 10MB vector. This would mean that ObjectInputStream is using very small buffer size. Is there a way to increase it, other than overriding read() to call super.read() with a bigger buffer and then doing a System.arrayCopy()?
    Thanks
    --kannan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • ObjectInputStream readObject loop

    When using the readObject method of ObjectInputStream the method blocks until it reads something from the stream.
    how would i put this method in a test loop?
    as when the method blocks and is waiting to read, if the output stream at the other end of the socket closes, then an IOException will be thrown.
    is there something i can write like, while(input != EOF)?
    cheers

    There is no object that a readObject call could return to indicate that it was at end of file. On files the available method lets you know when no more data is available, this method can't be used with sockets since the sender may pause between objects. If the sender closes a Socket Exception: Connection reset will be thrown, you can catch this and terminate. A better choice is to define an object that meand end of transmission. But this is not always feasible, if you must be able to send any arbitrary object.
    Here's an example of a simple object transfer
    Sending class:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class TestWO
         static public void main(String [] args)
              Socket sock;
              ObjectOutputStream oos;
              try
                   sock = new Socket("127.0.0.1",5050);
                   oos = new ObjectOutputStream(sock.getOutputStream());
                   for(int i = 0; i<args.length; i++)
                        Thread.sleep(2000);
                        System.out.println("writing "+args);
                        oos.writeObject(args[i]);
              catch(Exception e){System.out.println(e);}
    Receiving class:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class TestRO
         Socket sock;
         ObjectInputStream ois;
         ServerSocket ss;
         private void listen(int port)
              System.out.println("Listening on port="+port);
              try
                   ss = new ServerSocket(port);
                   sock = ss.accept();
                   System.out.println("call accepted");
                   ss.close();
                   receive();
              catch(Exception e){     e.printStackTrace();}
         static public void main(String [] args)
              new TestRO().listen(5050);
         void receive()
              System.out.println("starting receiver");
              try
                   ois = new ObjectInputStream(sock.getInputStream());
              catch(IOException e)
                   System.out.println(e);
                   return;
              boolean running = true;
              Object obj;
              while(running)
                   try
                        obj = ois.readObject();
                        System.out.println("object="+obj);
                   catch(SocketException e)
                        if(e.getMessage().equals("Connection reset")){System.out.println("closed by partner");}
                        else e.printStackTrace();
                        running = false;
                   catch(Exception ex){ex.printStackTrace(); running = false;}
              try
                   ois.close();
                   sock.close();
              catch(Exception e){}

  • StreamCorruptedException using readObject()

    I wrote a object to .ser file using writeObject().
    and then again opened the file for writing in append mode,
    and wrote again a object to the .ser file.
    now the problem is using readObject() for the first time retrieve the first object added.
    but again doing a readObject() does not return the second object added.instead it throws
    java.io.StreamCorruptedException.folowing is the sample code
              File file = new File("/home/dhans/travelcache/test.ser");
              ObjectOutputStream os = new ObjectOutputStream(
                   new BufferedOutputStream(new FileOutputStream(file)));
              HashMap hm = new HashMap();
              hm.put("cd", "1001");
              os.writeObject(hm);
              os.flush();
              os.close();          
              ObjectOutputStream os1 = new ObjectOutputStream(
                        new BufferedOutputStream(new FileOutputStream(file, true)));
    // OPENED FILE FOR append mode
                   HashMap hm1 = new HashMap();
                   hm1.put("cd1", "1002");
                   os1.writeObject(hm1);
                   os1.flush();
                   os1.close();          
              ObjectInputStream is = new ObjectInputStream(
                        new BufferedInputStream(new FileInputStream(file)));
              HashMap hm2 = (HashMap)is.readObject();
              HashMap hm3 = (HashMap)is.readObject(); // exception occurs HERE
              is.close();but if i add the two objects at a time like
              ObjectOutputStream os = new ObjectOutputStream(
                   new BufferedOutputStream(new FileOutputStream(file)));
              HashMap hm = new HashMap();
              hm.put("cd", "1001");
                    os.writeObject(hm);
                   HashMap hm1 = new HashMap();
              hm1.put("cd1", "1002");
              os.writeObject(hm1);using the readObject() two times does not throw any exception.
    but my requirement is i have to open the file for append mode again to write the second and successive objects .
    any help would be helpful.
    thanks,
    dhanasekaran

    Sory, I hadn't checked the src until u said. Coz I ws jst using the APIs.
    Nw that I've checked the src....here's the complete code that writes to the file
    public void write (File f) {
         try {
              ObjectOutputStream oos =
                         new ObjectOutputStream(new FileOutputStream(f));
              oos.writeObject(this);
              oos.close();
         catch (IOException e) {
              System.err.println("Exception writing file " + f + ": " + e);
    private void writeObject (ObjectOutputStream out) throws IOException {
         int i, size;
         out.writeInt (CURRENT_SERIAL_VERSION);
         out.writeObject(inputPipe);
         out.writeObject(outputPipe);
         out.writeObject (inputAlphabet);
         out.writeObject (outputAlphabet);
         size = states.size();
         out.writeInt(size);
         for (i = 0; i<size; i++)
              out.writeObject(states.get(i));
         size = initialStates.size();
         out.writeInt(size);
         for (i = 0; i <size; i++)
              out.writeObject(initialStates.get(i));
         out.writeObject(name2state);
         if(weights != null) {
              size = weights.length;
              out.writeInt(size);
              for (i=0; i<size; i++)
                   out.writeObject(weights);
         }     else {
              out.writeInt(NULL_INTEGER);
         if(constraints != null) {
              size = constraints.length;
              out.writeInt(size);
              for (i=0; i<size; i++)
                   out.writeObject(constraints[i]);
         }     else {
              out.writeInt(NULL_INTEGER);
         if (expectations != null) {
              size = expectations.length;
              out.writeInt(size);
              for (i=0; i<size; i++)
                   out.writeObject(expectations[i]);
         } else {
              out.writeInt(NULL_INTEGER);
         if(defaultWeights != null) {
              size = defaultWeights.length;
              out.writeInt(size);
              for (i=0; i<size; i++)
                   out.writeDouble(defaultWeights[i]);
         }     else {
              out.writeInt(NULL_INTEGER);
         if(defaultConstraints != null) {
              size = defaultConstraints.length;
              out.writeInt(size);
              for (i=0; i<size; i++)
                   out.writeDouble(defaultConstraints[i]);
         }     else {
              out.writeInt(NULL_INTEGER);
         if (defaultExpectations != null) {
              size = defaultExpectations.length;
              out.writeInt(size);
              for (i=0; i<size; i++)
                   out.writeDouble(defaultExpectations[i]);
         }     else {
              out.writeInt(NULL_INTEGER);
         if (weightsPresent != null) {
              size = weightsPresent.length;
              out.writeInt(size);
              for (i=0; i<size; i++)
                   out.writeObject(weightsPresent[i]);
         }     else {
              out.writeInt(NULL_INTEGER);
         if (featureSelections != null) {
              size = featureSelections.length;
              out.writeInt(size);
              for (i=0; i<size; i++)
                   out.writeObject(featureSelections[i]);
         } else {
              out.writeInt(NULL_INTEGER);
    if (weightsFrozen != null) {
    size = weightsFrozen.length;
    out.writeInt (size);
    for (i = 0; i < size; i++)
    out.writeBoolean (weightsFrozen[i]);
    } else {
    out.writeInt (NULL_INTEGER);
         out.writeObject(globalFeatureSelection);
         out.writeObject(weightAlphabet);
         out.writeBoolean(trainable);
         out.writeBoolean(gatheringConstraints);
         out.writeBoolean(gatheringWeightsPresent);
         //out.writeInt(defaultFeatureIndex);
         out.writeBoolean(usingHyperbolicPrior);
         out.writeDouble(gaussianPriorVariance);
         out.writeDouble(hyperbolicPriorSlope);
         out.writeDouble(hyperbolicPriorSharpness);
         out.writeBoolean(cachedValueStale);
         out.writeBoolean(cachedGradientStale);
         out.writeBoolean(someTrainingDone);
         out.writeInt(featureInducers.size());
         for (i = 0; i < featureInducers.size(); i++) {
              out.writeObject(featureInducers.get(i));
         out.writeBoolean(printGradient);
         out.writeBoolean (useSparseWeights);
    out.writeInt (transductionType);
    //Serialization of MaximizableCRF
    private static final long serialVersionUID = 1;
    private static final int CURRENT_SERIAL_VERSION = 0;
    private void writeObject (ObjectOutputStream out) throws IOException {
              out.writeInt (CURRENT_SERIAL_VERSION);
              out.writeObject(trainingSet);
              out.writeDouble(cachedValue);
              out.writeObject(cachedGradient);
              out.writeObject(infiniteValues);
              out.writeInt(numParameters);
              out.writeObject(crf);

  • Java Sockets - help with using objects

    I am new to java sockets, and need to come up with a way to send a user defined instance of a class across a basic client/server application.
    I can not find out how to do this. I read the tutorials, but my class can not be serialized. How can I send/recieve this instance of a user defined class?

    right off the top of my head, doesn't serialver just spit out a UID for a given set of classes?
    To mark a class as Serializable, just implement the java.io.Serializable class - then you could use the readObject/writeObject methods of the ObjectInputStream/ObjectOutputStream classes.
    Good luck
    Lee

  • JTable / ObjectInputStream

    Hey, guys.
    For some reason my JTable isn't updating properly. This is how things are supposed to work.
    The client sends a request to the server. The server queries the database, and then sends the result, as a vector, to the client. I have a JTable, that updates itself everytime the appropriate TAB is chosen. Now, the first time I click on the tab, the JTable shows me exactly what is in that table in the database. Then I make a change to the table in the database, choose the TAB again, but the table isn't updated. It is definitely updated in the database as I have checked that.
    This is what the server does:
    er.getItemsFromDB();
    Vector <EmailInfo> itemsList = er.getItemsList();
    try {
            objectoutputstream.writeObject(itemsList);
            objectoutputstream.flush();
    catch (Exception e){
            e.printStackTrace();
    }the receive is implemented as so:
        protected Object receiveObject(){
            Object obj = new Object();
            try {
                obj = objectinputstream.readObject();
            catch(Exception e){
                e.printStackTrace();
            return obj;
        }And the app does the following:
    Vector <EmailInfo> itemsList = (Vector <EmailInfo>) socket.receiveObject(); Now, it definitely works the first time I run the program. And so far, I know that the server queries the database perfectly everytime, and it sends out the changed data. But for some reason, when I readObject(), it seems to read in the old data the second time I use the readObject method.
    Anyone know what I'm doing wrong. Let me know if you need to see more code.
    Thanks.
    ...DJVege...

    I'll try and show you the process:
    private void refreshItemTable(){
            MyTableModel itemTableModel = new MyTableModel(itemColumnNames, getItemData());calls getItemData()
    private Object[][] getItemData(){
            socket.send(socket.GETITEMSFROMDB);
            Vector <EmailInfo> itemsList = (Vector <EmailInfo>) socket.receiveObject();
            Object[][] rdata = new String[itemsList.size()][7];
            for (int i = 0; i < itemsList.size(); i++){
                EmailInfo item = (EmailInfo)itemsList.get(i);
                rdata[0] = item.getArtikelID();
    rdata[i][1] = item.getArtikelName();
    rdata[i][2] = item.getArtikelFarbe();
    rdata[i][3] = "�" + item.getPreis();
    rdata[i][4] = "�" + item.getVersicherterVersand();
    rdata[i][5] = "�" + item.getExtraCost();
    rdata[i][6] = String.valueOf(item.getStock());
    return rdata;
    calls socket.receiveObject():
    protected Object receiveObject(){
            Object obj = new Object();
            try {
                obj = objectinputstream.readObject();
            catch(Exception e){
                e.printStackTrace();
            return obj;
        } This is what the server does to send:
    else if (command.equals(GETITEMSFROMDB)){
                            er.getItemsFromDB();
                            Vector <EmailInfo> itemsList = er.getItemsList();
                            System.out.println(itemsList.get(0).getArtikelFarbe());
                            try {
                                objectoutputstream.writeObject(itemsList);
                                objectoutputstream.flush();
                            catch (Exception e){
                                e.printStackTrace();
                        }calls getItemsFromDB():
    public void getItemsFromDB(){
            itemsList.removeAllElements();
            try {
                conn = createConnectionToDB();
                Statement st = conn.createStatement();
                ResultSet rset;
                EmailInfo data;   
                st.execute("select * from Artikels order by artikelID");
                rset = st.getResultSet();
                while (rset.next()){
                    data = new EmailInfo();
                    data.setArtikelID(rset.getString(1));
                    data.setArtikelName(rset.getString(2));
                    data.setArtikelFarbe(rset.getString(3));
                    data.setPreis(rset.getString(4));
                    data.setVersicherterVersand(rset.getString(5));
                    data.setExtraCost(rset.getString(6));
                    data.setStock(Integer.parseInt(rset.getString(7)));
                    itemsList.add(data);
                conn.close();
                //System.out.println("Closed Database Connection");
            catch (Exception e){
                e.printStackTrace();
                 try {
                    conn.close();
                    //System.out.println("Closed Database Connection");
                catch (SQLException ex){
                    //System.out.println("Can't close database");
                    System.exit(0);
        }Then the server calls getItemsList():
    public Vector <EmailInfo> getItemsList(){
            return ItemsList;
        }where itemsList is set as a class variable above:
    private Vector <EmailInfo> itemsList = new Vector <EmailInfo> (3, 10);Does that help at all?
    Regards.
    ...DJVege...

  • Session.readObject(..) v/s ReadObjectQuery

    Is there any difference between using
    session.readObject(DAO.class, expr) and
    ReadObjectQuery(DAO.class, expr)?
    Thanks,
    Rajiv

    Well, they're a very easy way to manage query re-use, and therefore reduce garbage collection.
    Additionally, since named query construct can be separated from named query execution, named queries provide an easy way to abstract toplink in a service layer. All your service layer would provide would be mechanisms for executing queries by name. Your service layer could then pass through to toplink.
    There are lots of benefits to this:
    1. Query reuse. Implies less garbage which implies faster performance.
    2. Abstraction. No toplink code outside the service layer (as you call it) (excepting perhaps valueholders).
    3. Cleanliness. Your code has one mechanism for executing queries. By name. Why have lots of confusing ways to do the same thing?
    4. Localization of queries. A surprisingly overlooked benefit. Named queries will normally be defined together, in one code location (eg 1 package). This makes it very easy to identify badly performing queries and re-write them without having to play hunt the expression builder.
    Christian

  • Custom Deserialization for a List of serializable objects

    I'm running into trouble creating custom deserialization using the readObject method.
    Here is the code the reads the blob from the database:
    Blob blob = rs.getBlob(idx++);
                InputStream iStream = blob.getBinaryStream();
                try {
                    ObjectInputStream oiStream = new ObjectInputStream(iStream);
                    Object object = oiStream.readObject();
                    List data = (List) object;
                    report.setData(data);
                catch (EOFException ignored) {}
                finally {
                    iStream.close();               
                }And my class:
    public class PerformanceReportRowInfo extends PerformanceInfo
        private static final long serialVersionUID = 20060406L;
        private String _dateStr;
        private long _queries;
        private void readObject (ObjectInputStream ois) throws IOException,
                ClassNotFoundException
            ObjectInputStream.GetField fields = ois.readFields();
            _dateStr = (String) fields.get("_dateStr", null);
            try {
                _queries = fields.get("_queries", 0L);
            } catch (IOException io) {
                int intQueries = fields.get("_queries", 0);
                _queries = (long) intQueries;
    }The reason custom deserialization is needed is because we are converting the "_queries" attribute from an int to a long, and do not want to have to replace all the blobs in our DB with long types.
    For some reason, however, the readObject method never gets called in the PerformanceReportRowInfo, and instead i continue to get the error message:
    java.io.InvalidClassException: PerformanceReportRowInfo; incompatible types for field _queries
    I even added logging to the readObject method to make sure it wasnt getting called, and my suspicion was confirmed, it was indeed not getting called. Is my problem related to the fact that it is extending another serializable object (in this case PerformanceInfo) that doesnt have a custom readObject method? Or is it because of how im converting the blob to a List in the first block of code? BTW, the exception occurs at this line:
    Object object = oiStream.readObject();
    Thanks for the help!

    It is Serializable and does not extend any other class (except Object of course), here is the full stack trace:
    Caused by: java.io.InvalidClassException: PerformanceReportRowInfo; incompatible types for field _queries
         at java.io.ObjectStreamClass.matchFields(ObjectStreamClass.java:2175)
         at java.io.ObjectStreamClass.getReflector(ObjectStreamClass.java:2070)
         at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:586)
         at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1552)
         at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466)
         at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1552)
         at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466)
         at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1699)
         at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
         at java.util.ArrayList.readObject(ArrayList.java:591)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:946)
         at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1809)
         at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719)
         at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
         at MyClass.readReport(MyClass.java:332)

  • InvalidClassException ImageIcon.$AccessibleImageIcon class incompatible

    Greetings,
    I cannot seem to find a solution for this problem, so I am turning to you - your help is greatly appreciated.
    Below is a snippet of some legacy code that has been deployed in an app running JRE 1.4.2.
    class NodeImage implements Serializable {
        final static long serialVersionUID = 2606889903904458364L;
        public Dimension dim;
        public transient Image img;
        public ImageIcon ii; //VERY PROBLEMATIC NOW!!!!
        public String name;
        public String description;
      }Now, with the application having been modified and upgraded to run on JRE 1.5.0, old serialized objects can no longer be read into the above class, because the ImageIcon.$AccessibleImageIcon serialVersionUID has changed. The exception being thrown is as follows:
    java.io.InvalidClassException: javax.swing.ImageIcon$AccessibleImageIcon;
    local class incompatible: stream classdesc serialVersionUID = -3994512798706967451,
    local class serialVersionUID = -1903458698681874148
            at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:519)
            at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1546)
            at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1460)
            at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1693)
            at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1299)
            at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1912)
            at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:468)
            at javax.swing.ImageIcon.readObject(ImageIcon.java:389)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            ...The object has no explicit readObject or writeObject methods.
    I have tried a variety of things - e.g. writing a new readObject method, and using java.io.ObjectInputStream.GetField fields = in.readFields(); but I cannot seem to find a way to read the offending field without the exception being thrown and the rest of the read process aborted.
    Is there ANY way around this?
    I don't care if the end result makes the ImageIcon ii field null. But because this is just one object in a serialized hierarchy, I just want to be able to get the dim, name, and description attributes and then continue loading the remainder of the object hierarchy.
    Thanks in advance for your help! Any insight would be great.
    .

    Your developers should have read the warning in the javadoc for javax.swing.ImageIcon before serializing ImageIcons across JDK versions.
    You may have to use JDK 1.4 to read these streams and write them out again using something other than classes with this warning when they occur.
    The only other thing I can suggest is a custom readObject method which doesn't call defaultReadObject() and instead picks apart the serialization protocol itself for the offending class(es), calling readObject() for all non-offending members.

  • Manual serialization and versioning

    Hi all
    I have a class with n fields that is serialized in this way:
    private void writeObject(ObjectOutputStream out) throws IOException {
    for (int i = 0; i < n; i ++){
    out.writeXXX(field_n);
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    for (int i = 0; i < n; i ++){
    in.readXXX(field_n);
    I have serialized versions of the class and I am reading them in my program.
    Now I have to add new field in the class. I intend to implement the write method in this way:
    private void writeObject(ObjectOutputStream out) throws IOException {
    for (int i = 0; i < n; i ++){
    out.writeXXX(field_n);
    out.writeXXX(newfield);
    But I have no idea how to implement the read method to work with the two versions.
    Does anyone know how to deal with this?

    I found a way to deal with the problem. Now my code looks like this:
    private void writeObject(ObjectOutputStream out) throws IOException {
    final ObjectOutputStream.PutField field = out.putFields();
    field.put(FIELD_VERSION, version);
    field.put(FIELD_DATA, toShow);
    out.writeFields();
    private void readObject(ObjectInputStream in)
    throws IOException, ClassNotFoundException {
    try {
    final ObjectInputStream.GetField field = in.readFields();
    int oldversion = field.get(FIELD_VERSION, 0);
    if (oldversion > 0) {
    toShow = (ArrayList) field.get(FIELD_TO_SHOW, toShow);
    } else {
    final ObjectStreamClass streamClass = field.getObjectStreamClass();
    ObjectStreamField [] o = streamClass.getFields();
    toShow = (ArrayList)field.get(o[1].getName(), new ArrayList());
    Looks like the data stored in the old way (directly with outputStream.writeObject()) can be taken from the GetField. So I am using PutField and GetField to write/read the data, and when I see the data was not written in the new way (
    int oldversion = field.get(FIELD_VERSION, 0);
    if (oldversion > 0) {*old data*/}
    ) I am reading the old objects wrote trough the writeObject method using the names of the variables I had wrote. I am not sure what exactly is specified in the serialization spec., but this works now.
    Hope this will be useful for someone
    Best Regards
    Zlatko

  • Activate a Midlet from an Applet

    Hi,
    I am trying to activate a Midlet from an Applet? Is this possible in any of the latest J2ME releases?
    Using SATSA I am able to send APDU commands from the Midlet to the Applet and start a scenario where my Applet and Midlet exchange information.
    Is this available in the opposite direction. I want that my Applet, when triggered by an event, be able to Activate\Wake Up the Midlet.
    I am a newbie to J2ME and after researching the web, still couldn't find an answer. Thanks for your help.
    Bye.

    You can communicate with servlet from an applet, using URL connection, and then send POST/GET methods through HTTP protocol, here is a code snippet,
    // applet side, this method will send a POST method to the servlet and then get url openstream to read a
    // returned object from the servlet, params should be in the form param1=value&param2=value etc...
    public Object getObjectFromServlet(String servletName,String params) {
        Object object = null;
        try {
          URL url = new URL(codeBase,
                            contextRoot + servletName + params);
          URLConnection con = url.openConnection();
          con.setUseCaches(false);
          InputStream in = con.getInputStream();
          ObjectInputStream result = new ObjectInputStream(in);
          object = result.readObject();
          result.close();
          in.close();
        catch (ClassNotFoundException ex) {
          System.err.println("ClassNotFoundException caught:" + ex.getMessage());
        catch (MalformedURLException ex) {
          System.err.println("MalformedURLException caught:" + ex.getMessage());
        catch (IOException ex) {
          System.out.println("IOException caught:" + ex.getMessage());
        return object;
    //servlet side
    public void doPost(HttpServletRequest request, HttpServletResponse response){
          //Extract all the necessary supplied parameters from the request object and configurations.
           String param1 = request.getParameter("param1");
           String param2 = request.getParameter("param2");
      try {
            ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
            out.writeObject(object);
            out.close();
          catch (IOException ioe) {
            System.err.println("IOException caught:" + ioe.getMessage());
    }

  • StreamCorruptedException : invalid Type Code AC .. In case of a network app

    Hi
    I am developing a peer-peer application here.
    What i have is a client and a server on each user, both running parallell.
    User A sends an object to User B through an ObjectOutputStream through the main thread.
    User B reads it using an ObjectInputStream and passes the object that it read, to a new ObjectOutputStream, to be passed to User C.
    User C just reads the incoming object using ObjectInputStream.
    This iteration runs successfully for the first run!
    The moment I go for the second iteration using User A, the method on User B throws a "invalid type code AC".
    class Main{
    Socket sock;
    psvm(String args[]){
    Client newCli = new Client();
    newCli.setSock(<Sets the sock after getting the port and IP address from the user>);
    sock = newCli.getSock();
    ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
    oos.writeObject(new Client());
    Class Server extends thread{
    public void run(){
    while(true){
    ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
    ois.readObject();
    I read through this post on this forum and "EJP" asks that one OOS and one OIS be maintained per socket.
    So what i did was add a setter method to the Client class which stores the Socket, and called the setter method instead of creating a new ObjectOutputStream object everytime. This way one ObjectOutputStream object would be maintained per socket per client class's instance.
    class Client{
    Socket sock;
    ObjectOutputStream oos;
    //Getter and setter for sock.
    getSock()....
    setSock()....
    //Getter and setter for ObjectOutputStream
    getOos()....
    setOos(){
    oos = new ObjectOutputStream(getSock().getOutputStream());
    When i do this, the initial iteration itself fails.
    I am posting the outline of my code since it is a big file. But if writing out a smaller version of the app and posting it here will help better understand the scenario, then I'll do it.
    I am re-posting this, coz in the previous posts regarding this same issue, i found that people were writing and reading on the application. While mine is a case of a client-server send and receive.
    I am just writing multiple times at the client and reading multiple times at the server. And each time i'm creating a fresh ObjectOutputStream object, and Client object.
    I don't close the streams since that closes the sockets, but i need to keep the sockets open and send multiple objects on the same socket.
    The explanation is a bit lengthy, so let me know if something is not clear. :)
    Thanks
    Akshay

    I'd be grateful if someone can throw some light on this issue, i have to get beyond this ASAP, and i cannot find a workaround at all.. :/

  • Java.lang.Exception problem .. help needed

    I have a class and i am trying to access a method of another class that is reading an object.
    public void read(String filename) throws Exception {
    String fn = filename;
    ObjectInputStream out = null;
    Object object = null;
    try {
    FileInputStream file = new FileInputStream(fn);
    out = new ObjectInputStream(file);
    object = out.readObject();
    out.close();
    } catch (java.io.IOException IOE) {
    if (out != null)
    try {
    out.close();
    } catch (Exception ex) {}
    throw IOE;
    When i am compiling the program it is giving me this error
    unreported exception java.lang.Exception; must be caught or declared to be thrown
    I'm quite new to java ... could you tell me how to catch this exception
    its in this part
    scoreTable.read("scores.txt");
    Thanks

    Try this :
        private void someMethod(){
            try{
                read("c:\\bank\\testobject.txt");
            }catch(IOException ex){
                ex.printStackTrace();
            }catch(ClassNotFoundException ex){
                ex.printStackTrace();
    //        you can use the object here
        Object object;
        public void read(final String filename)  throws IOException, ClassNotFoundException{
            ObjectInputStream out = null;
            object = null;
            try{
                out = new ObjectInputStream(new FileInputStream(filename));
                object = out.readObject();
            }finally{
                if( out != null ){
                    out.close();
        }

  • Problem reading objects

    Hi i am trying to read objects from i file i have written them to but cannot seem to get it goint any suggestions here are two errors but i am sure their are more
    ---------- javac ----------
    C:\university_class_work\cosc1309\Assignments\Assignment1\Bin2Text.java:26: incompatible types
    found : java.lang.Object
    required: java.io.ObjectInputStream
    while ((ins = ins.readObject()) != null) {
    ^
    C:\university_class_work\cosc1309\Assignments\Assignment1\Bin2Text.java:32: cannot resolve symbol
    symbol : method flush ()
    location: class java.io.ObjectInputStream
    ins.flush ();
    ^
    2 errors
    Normal Termination
    Output completed (1 sec consumed).
    import java.util.*;
    import java.text.*;
    import java.io.*;
    // Bin2Text.java
    // Assignment1
    // Created by dragon on Sun Mar 09 2003.
    // Copyright (c) 2003 __MyCompanyName__. All rights reserved.
    public class Bin2Text implements Serializable {
    public static void main(String[] args) throws IOException{
    String name;
    //PrintWriter out = null;
    Text2Bin p2b = new Text2Bin();
    StringTokenizer words = null;
    String line;
    try {
    PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter ("out.txt")));
    FileInputStream in = new FileInputStream ("in.bin");
    ObjectInputStream ins = new ObjectInputStream (in);
    while ((ins = ins.readObject()) != null) {
    PizzaEater myPizzaEater = new PizzaEater();
    ins.readObject(myPizzaEater);
    out.write (myPizzaEater);
    ins.reset ();
    ins.flush ();
    ins.close();
    out.close ();
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    catch (NegativeNumberException nne) {
    System.out.println ("NegativeNumberException message was: " +
    nne.getMessage());
    class NegativeNumberException extends Exception {
    * Default constructor setting NegativeNumberException to the default
    * as specified by API reference Exception
    public NegativeNumberException () {
    super();
    * a Constructor passing the number value of the exception and
    * returning it with feedback
    public NegativeNumberException (int slices) {
    super("Number entered: " + slices + " number must be positive.");
    }

    Hi i am trying to read objects from i file i have
    written them to but cannot seem to get it goint any
    suggestions here are two errors but i am sure their
    are more
    ---------- javac ----------
    C:\university_class_work\cosc1309\Assignments\Assignmen
    1\Bin2Text.java:26: incompatible types
    found : java.lang.Object
    required: java.io.ObjectInputStream
    while ((ins = ins.readObject()) != null) {
    ^I'm not sure what you're trying to do exactly, I think its retrieve the next object from ObjectInputStream, you'd probably want to use another variable of type Object
    C:\university_class_work\cosc1309\Assignments\Assignmen
    1\Bin2Text.java:32: cannot resolve symbol
    symbol : method flush ()
    location: class java.io.ObjectInputStream
    ins.flush ();
    ^
    2 errors
    Normal TerminationNo flush() for InputStream objects.
    Output completed (1 sec consumed).
    import java.util.*;
    import java.text.*;
    import java.io.*;
    // Bin2Text.java
    // Assignment1
    // Created by dragon on Sun Mar 09 2003.
    // Copyright (c) 2003 __MyCompanyName__. All rights
    reserved.
    public class Bin2Text implements Serializable {
    public static void main(String[] args) throws
    ws IOException{
    String name;
    //PrintWriter out = null;
    Text2Bin p2b = new Text2Bin();
    StringTokenizer words = null;
    String line;
    try {
    PrintWriter out = new PrintWriter (new
    r (new BufferedWriter (new FileWriter ("out.txt")));
    FileInputStream in = new FileInputStream
    Stream ("in.bin");
    ObjectInputStream ins = new ObjectInputStream
    Stream (in);
    while ((ins = ins.readObject()) != null) {
    PizzaEater myPizzaEater = new
    Eater = new PizzaEater();
    ins.readObject(myPizzaEater);
    out.write (myPizzaEater);
    ins.reset ();
    ins.flush ();
    ins.close();
    out.close ();
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    catch (NegativeNumberException nne) {
    System.out.println ("NegativeNumberException
    xception message was: " +
    nne.getMessage());
    class NegativeNumberException extends Exception {
    * Default constructor setting
    ing NegativeNumberException to the default
    * as specified by API reference Exception
    public NegativeNumberException () {
    super();
    * a Constructor passing the number value of the
    the exception and
    * returning it with feedback
    public NegativeNumberException (int slices) {
    super("Number entered: " + slices + " number must
    st be positive.");

Maybe you are looking for

  • Unable to open Messaging Server 6.2 through admin console 5.2

    my system is Sun Java(tm) System Messaging Server 6.2-3.05 (built Nov 23 2005) libimta.dll 6.2-3.05 (built 02:22:19, Nov 23 2005) Microsoft Windows 2000 version 5.2 (Build 3790) i installed Sun Java Enterprise System (directory, admin, messaging) ser

  • Error (13013) message when trying to open itunes.........

    I have just installed itunes - and now it says 'The itunes application could not be opened. An unknown error occured (13013)' Any ideas? I want to play with my new Ipod touch

  • Application Process Issue

    +(First off, we're using ApEx 4.0 through IE8)+ I have a report that serves as a 'shopping cart' of sorts, with a 'Remove' button to cancel items from it. But the 'Remove' button doesn't go to the page, it just leaves a blank white page. (Thankfully,

  • How to monitor message mapping in BPE

    Hello all, I use an integration process to do several mapping after each other. When I try to check the result of the first mapping in the BPE Log, I get the message "No message available for slection". I can open the input message from the Container

  • Icon not active in Y report

    Dear All I have currently developed a Y report on store consumption. In the report Total and sub total option is in deactivated mode. How to make it activate mode. With Regards Arun