Return Name of class from instance of that class

I think your requirement falls in the gap for apex but we have the ability to do one of following things:

We can retrieve the name of an object using code such as

String name = MyClass.class.getName(); //returns MyClass

We can check whether the instance of a particular type using

Boolean isSame = mc instanceof MyClass; //returns true

Or if we want to get the name from an instance of an unknown type we can do:

String name = String.valueOf(mc).split(':')[0];//returns MyClass

Hopefully one of those covers your need. See the discussion to a similar question here for more info.


This is an interesting hack as posted on the idea Method to get the Type of an Object (also Primitive Type not only SObject) by Robert Strunk:

public static String getObjectType(Object obj){

    String result = 'DateTime';
    try{
        DateTime typeCheck = (DateTime)obj;
    }
    catch(System.TypeException te){

        String message = te.getMessage().substringAfter('Invalid conversion from runtime type ');
        result = message.substringBefore(' to Datetime');
    }

    return result;
}

The parse conversion exception approach overcomes the caveat that using String.valueOf(obj).split(':')[0] does not work in scenarios where the Apex class' toString() method has been overriden and returns a value in a different format, as pointed out in this comment.


To answer the title of the question: to get the name of the class from within any class use this:

String CurrentClassName = String.valueOf(this).substring(0,String.valueOf(this).indexOf(':'));