Using readClassDescriptor() and maybe resolveClass() to permit Serialization versioning

前端 未结 5 1973
暗喜
暗喜 2020-12-10 08:11

I am investigating different options in the Java Serialization mechanism to allow flexibility in our class structures for version-tolerant storage (and advocating for a diff

5条回答
  •  我在风中等你
    2020-12-10 08:42

    I had same problems with flexibility like you and I found the way. So here my version of readClassDescriptor()

        static class HackedObjectInputStream extends ObjectInputStream
    {
    
        /**
         * Migration table. Holds old to new classes representation.
         */
        private static final Map> MIGRATION_MAP = new HashMap>();
    
        static
        {
            MIGRATION_MAP.put("DBOBHandler", com.foo.valueobjects.BoardHandler.class);
            MIGRATION_MAP.put("DBEndHandler", com.foo.valueobjects.EndHandler.class);
            MIGRATION_MAP.put("DBStartHandler", com.foo.valueobjects.StartHandler.class);
        }
    
        /**
         * Constructor.
         * @param stream input stream
         * @throws IOException if io error
         */
        public HackedObjectInputStream(final InputStream stream) throws IOException
        {
            super(stream);
        }
    
        @Override
        protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException
        {
            ObjectStreamClass resultClassDescriptor = super.readClassDescriptor();
    
            for (final String oldName : MIGRATION_MAP.keySet())
            {
                if (resultClassDescriptor.getName().equals(oldName))
                {
                    String replacement = MIGRATION_MAP.get(oldName).getName();
    
                    try
                    {
                        Field f = resultClassDescriptor.getClass().getDeclaredField("name");
                        f.setAccessible(true);
                        f.set(resultClassDescriptor, replacement);
                    }
                    catch (Exception e)
                    {
                        LOGGER.severe("Error while replacing class name." + e.getMessage());
                    }
    
                }
            }
    
            return resultClassDescriptor;
        }
    

提交回复
热议问题