首页 文章

Groovy - 使用metaClass删除类字段瞬态修饰符

提问于
浏览
0

我们有一个简单的Groovy类:

class A implements Serializable {
   transient Integer t // this field is transient in the serialization process
   Object o
}

我们知道,我们可以使用Groovy的metaClass属性(元编程)在运行时修改类的属性和方法 .

我不想做的是: remove the 'transient' modifier from the 't' property of the A class and let it to serialize this field . 我需要使用metaClass或其他机制在RUNTIME中执行此操作 .

重新编译,重新创建一个类将不是一个解决方案 . 我在服务器上部署并运行了这个类,我唯一可以做的就是通过远程groovy-shell改变它的元行为 .

2 回答

  • 0

    我已经有了这个,我不相信这是可能的

    即使使用反射并在类的声明字段上设置修饰符,序列化仍会跳过该属性

    我认为唯一的解决方案是编写自己的序列化例程,忽略transient修饰符 .

    或者当然,改变 class (但你说这是不可能的)

  • 0

    如果要控制瞬态字段的序列化,请使用json-io(https://github.com/jdereg/json-io)Java / Groovy序列化库 . 它允许您关联一个类,该类将告诉序列化程序要序列化哪些字段 . 此列表指定为字符串列表 . 换句话说,您可以逐个类地有效地告诉序列化程序您希望序列化哪些字段 . 因此,如果您只有一个类导致问题,请指定要序列化的字段,包括瞬态字段,它们将被序列化 .

    def custom = [(A.class):['t', 'o']]
    def args = [(JsonWriter.FIELD_SPECIFIERS):custom]
    def json = JsonWriter.objectToJson(root, args)
    println json
    

    如果您有多个具有要序列化的瞬态字段的类:

    def custom = [(A.class):['t', 'o'], (B.class):['field1','field2'], ...]
    def args = [(JsonWriter.FIELD_SPECIFIERS):custom]
    def json = JsonWriter.objectToJson(root, args)
    println json
    

    (A.class)在括号中,因为如果Groovy Map中的键不是String,则它必须在括号中 .

相关问题