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?
Asked
Active
Viewed 5,829 times
17
4 Answers
13
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. – Phil Hawthorn Oct 16 '12 at 19:24
7
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.
Daniel Ballinger
- 102,288
- 39
- 270
- 594
1
From Trailhead's Apex Recipes, covers Inner Classes as well.
/**
* @description It can be useful to know what the type of an object
* is at runtime. This is especially useful when you're dynamically
* instantiating objects in code from the name of a class.
*
* I'm not generally a fan of relying on an exception to make logic
* decisions, but in this case I'll make an exception as this is the
* cleanest method I've yet found for efficently determining an objects
* class name that covers edge cases where the object is of an inner class'
* type.
*
* This method parses a TypeException for the true name of a class.
* It generates the exception by forcing a cast from the Object parameter
* to DateTime. If no typeException occurs, we know it's a dateTime object.
* @param obj
* @return `String`
*/
public static String getUnkownObjectType(Object obj) {
String result = 'DateTime';
try {
DateTime typeCheck = (DateTime) obj;
} catch (System.TypeException expectedTypeException) {
String message = expectedTypeException.getMessage()
.substringAfter('Invalid conversion from runtime type ');
result = message.substringBefore(' to Datetime');
}
return result;
}
Christian Szandor Knapp
- 3,074
- 2
- 16
- 41
0
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
Pradeepkumar'2552866
- 75
- 11
-
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 – Pradeepkumar'2552866 Oct 13 '16 at 17:39
-
Caveat: The bigger the class, the more CPU is needed for
String.valueOf(this)– Christian Szandor Knapp Aug 30 '22 at 11:37
System.debug(String.valueOf(new MyClass()));//MyClass:[]System.debug(String.valueOf(new PageReference('')));
– Matt and Neil Jan 16 '13 at 16:36//System.PageReference[]myInstanceisnull, I think only you can know what you intended to hand it it. What's your requirement exactly? Could be a good question to ask. – Matt and Neil Dec 26 '13 at 22:42