Overriding class signature in java

I have the following class in a file .jar

(library file):

class A{
//someimplementation
}

      

I would like to go to the interface implements Serializable

like this:

class A implements Serializable {
//the same implementation as present in classA
}

      

I don't want to decompile the jar file by changing the class signature and then archiving it again after compilation.

Is there a way how to write hooks to achieve this? Please provide any pointers / suggestions. My ultimate goal is to implement Serializable interface without changing the jar file.

+3


source to share


1 answer


You can probably achieve this with the Serialization proxy pattern (Effective Java 2nd Edition, item 78)

A few links about the template:

http://jtechies.blogspot.com/2012/07/item-78-consider-serialization-proxies.html

http://java.dzone.com/articles/serialization-proxy-pattern



Control: instance control in Java without enumeration

Create a new class that extends A

and Serializable

. However, to avoid serialization errors since A

it is not serializable, you need to create a SerializationProxy that creates a new instance via a constructor or factory method instead of the usual Java Serialization mechanism, which explicitly sets fields outside of any constructor.

public class MySerializableA extends A implements Serializable{
    private final Foo foo;
    private final Bar bar;
   ...

    private Object writeReplace() {
         return new SerializationProxy(this);
    }
    //this forces us to use the SerializationProxy
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
         throw new InvalidObjectException("Use Serialization Proxy instead.");
    }


   //this private inner class is what actually does our Serialization
   private static class SerializationProxy implements Serializable {
        private final Foo foo;
        private final Bar bar;
   ...

    public SerializationProxy(MySerializableA myA) {
        this.foo = myA.getFoo();
        this.bar = myA.getBar();
        ...//etc
    }

    private Object readResolve() {
        return new MySerializableA(foo, bar,...);
    }

}
} 

      

The only drawback is that you want to serialize A

, you will have to wrap it in MyA

. but on deserialization, casting to A

will work fine.

+1


source







All Articles