I'm looking for a way to get the name of an object instance at run-time. Is it possible to to determine the class name (as a string) of an instance? i.e. is there an Apex equivalent of the Java myInstance.getClass().getName() or any tricks to achieve just that?
3 Answers
instanceOf
verifies at runtime whether an object is actually an instance of a class...but you would have to write the conditions to check for them all. Also getSObjectType
will describe an sObject.
-
1Thanks, actually I've just realised that since I own all of the classes I'm interested in I can implement my own getName() method. Oct 16, 2012 at 19:24
Voting for the idea Method to get the Type of an Object (also Primitive Type not only SObject) would be a good long term solution.
You can use something like below:
String.valueOf(this).substring(0,String.valueOf(this).indexOf(':'));
Sources
@pbattisson's Ans
@Matthew's Ans in SF blog
-
2
-
Agreed, I didn't try it for inner class though. Do we have any work around to get the name of inner class? Thanks Oct 13, 2016 at 17:39
System.debug(String.valueOf(new MyClass()));
//MyClass:[]
System.debug(String.valueOf(new PageReference('')));
//System.PageReference[]