Groovy - remove class field transient modifier using metaClass

Go To StackoverFlow.com

0

We have a simple Groovy class:

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

as we know, we can modify properties and methods of a class like that in runtime using Groovy's metaClass property (metaprograming).

What I wan't to do is: remove the 'transient' modifier from the 't' property of the A class and let it to serialize this field. I need to do this IN THE RUNTIME using metaClass or another mechanism.

Recompiling, recreating A class won't be a solution. I have this class deployed and running on the server and the only thing I can do with it is changing it's meta-behavior via remote groovy-shell.

2012-04-04 20:37
by user1313790


0

I've had a go at this, and I don't believe it's possible

Even with using reflection and setting the modifiers on the declared field from the class, serialization still skips the property

I think the only solution would be to write your own serialization routine, ignoring the transient modifier.

Or of course, change the class (but you say this isn't possible)

2012-04-05 08:31
by tim_yates


0

If you want to control serialization of transient fields, use the json-io (https://github.com/jdereg/json-io) Java / Groovy serialization library. It allows you to associate a class that will tell the serializer what fields to serialize. This list is specified as a String list. In other words, you can effectively tell the serializer which fields you want serialized, on a class by class basis. So if you only have one class causing you issues, specify which fields you want serialized, including the transient fields, and they will get serialized.

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

If you had more than one class that had transient fields to serialize:

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

The (A.class) is in parenthesis because a key in a Groovy Map needs to be in parenthesis if it is not a String.

2015-01-26 17:05
by John DeRegnaucourt
Ads