You need to sign in to do that
Don't have an account?
Sayali
Identifying if object is of type Set or List at runtime
Hello,
In Apex, at runtime we want to check if Object obj is of type Set or List where the type of elements in Set/List can be anything like String, Integer etc.
obj (of type Set<String>) instanceOf Set<Object> returns false and we want to avoid having if statements for each possible type of set.
Any pointers would be of great help.
-Sayali
There's no generic way to find out the type that I'm aware of, but you can use exception handling to help here. Try to cast the object to a set of objects and if that fails, try to cast to a list. E.g.
produces the following output:
Thanks for the quick reply.
However, it doesn't work when it is Set. We can't type cast Set<String> to String<Object>, so even though it is set we won't be able to figure it out.
Please correct me if I am missing something.
Thanks,
Sayali
Whats the original problem? If you don't mind my asking. I would say this is a more or programmatic issue.
Yes Auyon. It is a programmatic issue. However, I am not able to figure out any way to get this done.
My problem is, depending on the type of Object I want to do some processing. The type can be set and list also, of which element type can be anything again.
For other types like simple String, Integer.. I could use instanceOf operator, but for list and set not able to find any way.
I hope the problem is clear now.
Well, internally Apex writes java servlets and therefore very much aligned to Java's rules. So any relevant solution you find in Java should ethically work in Apex as well.
But, since we are trying to get our hands dirty...So just to understand do we need to know whether the object is a LIST or a SET or also what it is a LIST or SET Of? Because, as in Java although you cannot do a instanceOf in List or Set but the elements which they carry you can.
Appreciate if you can share some snippets, we can treat that as a starting point.
Sorry, I won't be able to share the code snippet.
Knowing the object is a List or Set would suffice here.
I will post a solution if I find one
You could try to cast to a set of objects and then inspect the TypeException error message to see if it refers to a different type of set, in which case you know it is a set. Its a bit fragile, in that if SFDC change the exception message it would stop working.
The only other thing I can think of is to use the String.valueOf() method and inspect the output. A set will be comma-separated values bound by braces, while a list is comma-separated values bound by brackets. Still fragile though, as the object could be a string that is formatted that way, so its likely to be some combination of use String.valueOf then try to cast it and see if you get an error.
There is no way to inspect an instance though - I've done some digging and the advice every time is to build a long list of if statements.
Thanks Bob.