在运行时向序列化对象添加额外字段

时间:2017-04-06 06:18:29

标签: serialization javassist

我想在对象中添加一个额外的字段(例如UUID),即在运行时使用javassist或反射进行序列化或已经序列化。

有可能吗?

2 个答案:

答案 0 :(得分:0)

简短回答

你无法按照自己的意愿去做,但也许还有其他方法

答案很长

所以让我们从一些定义开始:

Javassist :是一个用于在Java中编辑字节码的类库。它使Java程序能够在运行时和.asDoubles()定义新类。

反射:是Java编程语言中的一项功能。它允许执行Java程序modify a given class file when the JVM loads it自身,以及examine or introspect程序。例如,Java类可以获取其所有成员的名称并显示它们。

因此,当我使用manipulate internal properties突出显示时,您可以轻松地向类添加字段,但Javassist(意味着当JVM将类加载到其内存中时)。

使用only at load time可以在类的属性中查找甚至修改它们,但是reflection

我的建议

如果这对您的用例可行,我现在不知道,但解决方案可能同时使用它们:

  1. 使用no way off adding new properties将UUID字段添加到加载时可能需要它的类
  2. 在序列化对象之前,您可以使用Javassist将此UUID字段实际设置为所需的值,然后将其序列化

答案 1 :(得分:0)

实际上,没有反射就可以在不需要任何窗口的情况下使用要添加自定义属性的对象的类 - 可以通过首先将对象转换为这样的属性映射来完成,

这是我为此编写的一种方法,

     /**
     * To convert the current Object to a AttributeMap. This allows for using this map
     * to add to it in a subclass additional attributes for Serialization. It would be
     * required in a scenario when you want to alter the simple Jackson Serialization
     * methodology(where you just annotate the fields to be included in Serialization
     * and that's it.). A non-simple scenario would involve adding custom fields decided
     * at runtime 
     * @return The AttributeMap of this object.
     */
    protected Map<String, Object> toAttributeMap(Object object){
        return objectMapper.convertValue(object, new TypeReference<Map<String, Object>>() {
        });
    }

现在,您可以为该对象添加此属性映射,然后将() - 放入您的字段并将其转换为可能的JSON字符串。

关于答案的说明:

  • 它使用Jackson的Object Mapper API。
  • 它不使用JavaAssist。
相关问题