In some situations, it can be useful to be able to determine the names of the current class and method dynamically instead of using hard-coded strings. I find this particularly useful for logging purposes. I have a helper class which writes to the system log when certain exceptions are triggered. As input to this helper class (or rather the method writing to the system log) I want to provide the names of the class and method where the exception was raised.

Determining the name of the current class

SAP provides the class CL_ABAP_CLASSDESCR for determining some class attributes dynamically. To determine the name of the current class, the following code snippet can be used:

DATA(lv_class_name) = cl_abap_classdescr=>get_class_name( me ).

LV_CLASS_NAME will contain the class name in the following format: \CLASS=ZCL_MY_CLASS

Determining the name of the current method

The only approach I've found for determining the name of the current method is by using a function module to read the call stack. If you are aware of a better way of doing this, please leave a comment! The call stack approach looks like this:

DATA lt_callstack TYPE abap_callstack.

    max_level = 1
    callstack = lt_callstack.

DATA(lv_method_name) = lt_callstack[ 1 ]-blockname.

LV_METHOD_NAME will contain the method name in the following format: MY_METHOD

Happy coding!

If you would like to comment on this post, please head over to SAP Community.