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)
}
}
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityHow 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)
}
}
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
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);
}
}