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?

  • 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[] Jan 16 '13 at 16:36
  • 1
    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. Jan 16 '13 at 16:40
  • I thought you owned all the classes :P Jan 16 '13 at 16:56
  • 1
    @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. 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

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.

  • 1
    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. 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.


You can use something like below:


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

  • 2
    this doesn't return the fully qualified name for inner classes.
    – NSjonas
    Oct 10 '16 at 18:17
  • 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 '16 at 17:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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