How to get the Runtime-Type of an Object dynamically (for Primitive Data Types and SObjects)

Is it possible to get the Type of an Object (it’s not an SObject)?

String s = 'test';
doSomething(s);

public static void doSomething(o Object) {
    // need to find out if o is a string or an integer
    type = IsThereAMethodToGetTheTypeOf(o) // ?
    if(type='String') {
        // do something for strings here ....
    } else {
        // do something else ....
    }
}

I think the Type class can’t help me, because it has no way to get the type of an existing object instance, right? Any there any other way?

Since there is most likely no perfect solution possible within the current platform limitations, I posted an Idea on IdeaExchange here: https://success.salesforce.com/ideaView?id=08730000000l9wHAAQ

For SObject I have already this

public static string getType(SObject obj) {
    if(obj==null) return '';
    return obj.getSObjectType().getDescribe().getName()+'';
}

Answer

Thanks to the comment of @KeithC I was able to go on with my research and as a result, it seems not possible to get a primitive data-type dynamically as a string. There are concepts to come close to it by the usage of instance of or try/catch in brute-force-like manner.

Since the primitive types are just a few, this workaround with instanceof seems acceptable for all types excepts of collections.

For list, map and set actually I was not able to find a satisfactory solution. Brute-force is not a general option, because of infinite possibilities. String.valueOf() can give a clue but not very much: for set and map, it returns a serialization wrapped in {} and for list it’s wrapped in ().

Thanks to the feedback of @sfdcfox to try instanceof List<object>, map<object, object>, and set<object>, we seem to be able to detect lists. Unfortunately it does not work for maps and sets. This are my results:

object o;
o = new map<string,object>{}; 
system.debug( o instanceof map<string,object> ); // ==> true
system.debug( o instanceof map<object,object> ); // ==> false
o = new list<string>{}; 
system.debug( o instanceof list<string> ); // ==> true
system.debug( o instanceof list<object> ); // ==> true : only here it works
o = new set<string>{}; 
system.debug( o instanceof set<string> ); // ==> true
system.debug( o instanceof set<object> ); // ==> false

Any better approaches for collections are welcome!

The documentation to this topic is rare, as @mast0r said.

This links were helpful for me coming to this conclusion:

Attribution
Source : Link , Question Author : Uwe Heim , Answer Author : Community

Leave a Comment