2

Background

I would like to be able to dynamically set properties of an Object (not SObject).

Given this class:

public class Invoice {
    public String Ref { get; set; }
}

I would like to be able to do this:

Invoice inv = new Invoice();
inv.put('Ref', 'REF123');

But when I do Execute Anonymous Apex with above code, I this error:

ERROR: Compilation failed.
! ERROR: Line: 3, Column: 12
! Method does not exist or incorrect signature: void put(String, String)
! from the type Invoice
ERROR: Execution failed.

Question

  1. Is it possible to dynamically set properties of an Object (not SObject) using Apex?
  2. How would I dynamically set a property of an Object using Apex?
3

For some isolated cases - yours is one of them - there is this (ab)use of the serialize methods:

Invoice inv = (Invoice) JSON.deserialize(JSON.serialize(new Map<<String, Object>{
    'Ref' => 'REF123'
})), Invoice.class);

Here, the capability of JSON.deserialize to create an instance of the specified type and set the properties of the instance is being used.

But in general, Apex is missing the map-like behavior for objects or a reflection API.

|improve this answer|||||
  • 1
    I should add, on a tangent, that I frequently use this capability in unit tests to mock up objects that have normally read-only fields. – Charles T Apr 28 '19 at 15:37
  • Hi @CharlesT, I had assumed that the properties had to be public, but your comment makes me wonder... – Keith C Apr 28 '19 at 16:07
1

In addition to Keith's answer, you can use deserializeUntyped to change an Object that already exists. Keep in mind that the code below is going to copy the object, so any other references will still reference the old value.

Invoice inv = new Invoice();
inv.Ref = '123';
Map<String, Object> invMap = (Map<String, Object>)JSON.deserializeUntyped(JSON.serialize(inv));
invMap.put('Ref', '456');
inv = (Invoice)JSON.deserialize(JSON.serialize(invMap), Invoice.class);
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.