Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
String.valueOf(myInstance) will get you pretty close - works with built in classes too... class MyClass {} System.debug(String.valueOf(new MyClass())); //MyClass:[] System.debug(String.valueOf(new PageReference(''))); //System.PageReference[] – bigassforce Jan 16 '13 at 16:36
Yes - thanks, only trouble is with that if someone has overridden the toString() method in the class it may return something other than the class name, i.e. you can't always rely on it. – Phil Hawthorn Jan 16 '13 at 16:40
I thought you owned all the classes :P – bigassforce Jan 16 '13 at 16:56
@user320 - lol, yes I do and I know that I have overridden toString() (for a good reason too) and that it won't work in my use case. – Phil Hawthorn Jan 16 '13 at 17:05
@user320 your idea works well unless myInstance has a value of null. How would one work around this? – cropredy Dec 26 '13 at 22:15
up vote 9 down vote accepted

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.

share|improve this answer
Thanks, 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

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.

share|improve this answer

You can use something like below:


@pbattisson's Ans
@Matthew's Ans in SF blog

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.