5

I have many Custom Objects in my package that have a common custom field Version__c. One part of my app serializes and deserializes records to/from Json. While deserializing I want to change this Version field for any record which is of a type that has this field.

The code looks like this:

    private SObject createVersion(SObject oldRecord) {
        SObject newRecord = oldRecord.clone();

        if(isFieldAvailableOn('Version__c', oldRecord)) {
            newRecord.put('Version__c', oldRecord.Version__c);
        }

        return newRecord;
    }

How can I implement isFieldAvailableOn(String fieldName, SObject record) without consuming Describe call?

  • 2
    I ended up giving this answer to something similar the other day, it actually included both options described below. I ended up leaning to the JSON variant, due to my concerns over the performance overhead of generating exceptions (runtime having to snapshot the stack, in Java this has been historically expensive), take a look, it may not apply to you as much if its something you have to do less, salesforce.stackexchange.com/questions/24336/… – Andrew Fawcett Jan 23 '14 at 16:17
  • @AndrewFawcett As I understood Stephen the JSON solution does NOT check if a field exits on a the object type but only was queried on a certain record. That's not what I need. Image I loop over arbitrary records of arbitrary types and want to touch each record where its type has field a. – Robert Sösemann Jan 24 '14 at 10:45
  • Ok i see, then my advice is to ensure you do some volume testing, as i have a feeling it maybe quite CPU intensive, and thus the CPU Governor might come into play, anyway, thanks for clarificaiton, and good luck! :-) – Andrew Fawcett Jan 27 '14 at 12:35
4

You can simply wrap your attempt to read or write the Version field in a try-catch block. An exception means the field is not present, not writeable, or the wrong data type. The exception thrown will describe which scenario occurred.

|improve this answer|||||
  • This is a solid solution. Just be careful if you are going to use this and put it in a big loop as raising an exception has a performance hit. – lindon fox Jul 15 '15 at 12:52
9

How about a JSON roundtrip:

SObject so = new Account(Name='foo');
String s = JSON.serialize(so);
Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(s);
system.debug(m.keySet().contains('Name'));

This will not tell you if the sobject definition has the field, but only if the instance has it (has been set, or has been read form the db).

|improve this answer|||||
  • Sorry @Stephen but that's what I am interested in ;) – Robert Sösemann Jan 24 '14 at 10:42

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.