2

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) 
    }
}
1

2 Answers 2

7

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]);
            m.find();
            system.debug(
                m.group(1)
            );
        }
    }
}

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
5

There is this compile-time checked but dangerous when code is cut and pasted approach:

public class MyClass{
    public static void doSomething(){
        // get here the name of the class (MyClass) 
        // by calling getClassName()
    }
    private String getClassName() {
        return String.valueOf(MyClass.class);
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .