Application Development Blog Posts
Learn and share on deeper, cross technology development topics such as integration and connectivity, automation, cloud extensibility, developing at scale, and security.
cancel
Showing results for 
Search instead for 
Did you mean: 
johan_wigert
Active Participant
16,045

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.

CALL FUNCTION 'SYSTEM_CALLSTACK'
EXPORTING
max_level = 1
IMPORTING
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!





This blog post first appeared on the Developer Voyage blog at https://www.developervoyage.com/2019/09/13/determine-the-current-class-and-method-names.html


9 Comments
Labels in this area