Passing Objects to Future Annotated Methods

The future annotation is a great feature on the Salesforce Platform to allow you to execute custom logic asynchronously. I often use them to perform callouts within the context of a database trigger. However, one of the restrictions of future annotations is that you can not pass sObjects or objects as arguments to the annotated method. I regularly use encapsulation to pass a collection of parameters, or even an sObject, but this won’t work in @future method:

But thankfully there is a way you can do. The secret sauce is the JSON serialize|deserialize methods.

Take the example of an AddressHelper object referred to above. This is encapsulated convenience object to help me pass around address details. (note:For simplicity, this helper object just includes strings, but it could easily include other types including objects, sobjects, collections etc.)

That’s it. JSON.serialize|deserialize makes it amazingly simple to pass objects, even ones with complex nested relationships, to @future annotated methods. There are time though that a particular object can not be serialized due to the underlying inheritance structure. One such example is the Pattern class in Apex.

To handle these outliers, I often create my own custom getSerializable() method on my custom object. For example, I use this strategy within the Chatter Blacklist app to pass a patternHelper object to an @future method.

Nice article! I’ve always used lists of Ids and grab the data once in the future method. But I’ll definitely consider this approach in the future (wondering why I didn’t think of this before…) One thing I noticed is the less-than/greater-than blocks of code got stripped out.

quintonwall

Damn CSS. Thanks for picking it up. I fixed it now.

Anonymous

That’s a neat trick! Will definitely give that a spin over using ids and queries.

Anonymous

The trick out now!, this can be considered for Javascript Remoting feature as well, you can serialize js object and pass it string.

mohit srivastav

Excellent post!Nice to know this way of passing parameters in future calls.

Nice post quintonwall, what I am left with, after reading this post is pros/cons of re-querying required records by ids in FUTURE context vs deserialize JSON to restore the object back.

A few points that are bugging me are :

– If the custom object is transformed out of few calculations in sobjects, we might not be seeing the latest and greatest information at present in database. As we might be using a stale JSON representation of Sobject info, at the time when future method is invoked.

@Quinton Wall , I still doubt if currAddress = (AddressHelper) JSON.deserialize(ser, AddressHelper.class); will return the whole list of AddressHelper.How can AddressHelper currAddress can hold the list of AddressHelper?