开发者

Java deserialization question

For re开发者_如何学编程use reasons I have wrapped my current serialization/deserialization services in an abstract generic class, which is compiled in a shared JAR across the project. I need to serialize objects to String

The class can be extended and a type can be specified for it in other JARs/WARs (yea, this is a web application).

When I made my first deserialization tests from within the same WAR it all worked fine, but now that I moved the abstract class into another JAR I get a ClassNotFoundError when deserializing.

The base class is structured as follows:

public abstract class ConverterBase<T extends Serializable> {

    public final Object getAsObject(String str) {
        //Use java.io serialization services from the base64 representation
        try {
        ByteArrayInputStream ba = new ByteArrayInputStream(decoder
                .decodeBuffer(str));
        try {
            ObjectInputStream is = new ObjectInputStream(ba);
            try {
                Object ret = is.readObject();
                return ret;
            } finally {
                is.close();
            }
        } finally {
            ba.close();
        }
    } catch (Throwable ex) {
        return null;
    }
    }

    public final String getAsString(Object obj) {
        //simply do the opposite
    }
}

It is structured such a way in order to allow future changes impact all subclasses (ie. avoid base64, be more efficient...). For now, the java.io solution is a temporary implementation.

Then I have the following inside the same WAR:

public class MyPojo implements Serializable {
    //Stuff
}

public final class MyPojoConverter extends ConverterBase<MyPojo> { }

The class that extends this one is in a different archive than the abstract class and is specialized on an type of that WAR.

What could I do to avoid that error?

Thank you


If you want to store the data as String, I would use XML or JSon to serialise your objects with a tool like XStream. These tools are not sensitive to change in packages, class names, parent classes, interfaces or method changes.


The ObjectInputStream must be able to access all the classes which are used in the serialized objects.

Normally it should be enough if the code creating the thread (e.g. its classloader) can load each class mentioned in the stream. Make sure this is the case. (I'm not really sure about your class loader structure in your application container. If you provide more information about this, maybe others can help.)

For more complicated cases, you can create a subclass and override resolveClass there.


This is probably a class loading issue (yeah, of course). If I got you right, the problem occurs from within your WAR, i.e. a JSP or servlet. Please provide your stack trace, I'm not sure, which class cannot be found.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜