Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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[] –  user320 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. –  Phil Hawthorn Jan 16 '13 at 16:40
    
I thought you owned all the classes :P –  user320 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. –  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? –  crop1645 Dec 26 '13 at 22:15

1 Answer 1

up vote 8 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
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. –  Phil Hawthorn Oct 16 '12 at 19:24

Your Answer

 
discard

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.