[SalesForce] Getting class name from static method

How can I get the class name from a static method? Code example:

public class MyClass{
    public static void doSomething(){
        // get here the name of the class (MyClass) 

Best Answer

There's no "direct" method for this; the usual way to do this is to construct a stack trace and then parse it:

public class q225429 {
    public static void test() {
        try {
            throw new MathException();
        } catch(Exception e) {
            Pattern p = Pattern.compile('\\.(\\w+)\\.test');
            Matcher m = p.matcher(e.getStackTraceString().split('\n')[0]);

Example output:

15:08:43.4 (4117534)|EXECUTION_STARTED
15:08:43.4 (4123179)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
15:08:43.4 (13554739)|USER_DEBUG|[9]|DEBUG|q225429
15:08:43.4 (13632020)|CODE_UNIT_FINISHED|execute_anonymous_apex
15:08:43.4 (15061770)|EXECUTION_FINISHED