[ABAP] Transienter Code / Dynamisch ABAP-Code generieren und ausführen

DATA: progname TYPE program.
DATA: msg TYPE string.
DATA: lin TYPE i.
DATA: wrd TYPE string.
DATA: off TYPE i.
DATA: mid TYPE trmsg_key.
DATA: sid TYPE string.

DATA(it_code) = VALUE stringtab( ( |PROGRAM SUBPOOL.| )
                                 ( |CLASS main DEFINITION.| )
                                 ( |  PUBLIC SECTION.| )
                                 ( |    CLASS-METHODS show| )
                                 ( |      IMPORTING| )
                                 ( |        i_txt TYPE string| )
                                 ( |      RETURNING VALUE(ret_val) TYPE string.| )
                                 ( |ENDCLASS.| )
                                 ( |CLASS main IMPLEMENTATION.| )
                                 ( |  METHOD show.| )
                                 ( |    WRITE: / i_txt.| )
                                 ( |    ret_val = \|\{ i_txt \} - Return value.\|.| )
                                 ( |  ENDMETHOD.| )
                                 ( |ENDCLASS.| ) ).

* Subroutinen-Pool im ABAP-Speicher des akt. Programms erzeugen
* it_code wird übergeben, Programmname wird temporär vom System vergeben
GENERATE SUBROUTINE POOL it_code NAME progname MESSAGE msg LINE lin WORD wrd OFFSET off MESSAGE-ID mid SHORTDUMP-ID sid.

CASE sy-subrc.
  WHEN 0. " ok
    TRY.
* dynamischen Klassennamen ermitteln
        DATA(lv_class) = |\\PROGRAM={ progname }\\CLASS=MAIN|.
        DATA: ret TYPE string.

        WRITE: / 'Programm:', progname.
        WRITE: / 'Class:', lv_class.
        SKIP.

* statischer Methodenaufruf
        CALL METHOD (lv_class)=>show
          EXPORTING
            i_txt   = 'Static call'
          RECEIVING
            ret_val = ret.

        WRITE: / ret.

* dynamischer Methodenaufruf
        DATA o_ref TYPE REF TO object.
        CREATE OBJECT o_ref TYPE (lv_class).
        CALL METHOD o_ref->('SHOW')
          EXPORTING
            i_txt   = 'Dynamic call'
          RECEIVING
            ret_val = ret.

        WRITE: / ret.

      CATCH cx_root INTO DATA(e_text).
        MESSAGE e_text->get_text( ) TYPE 'I'.
    ENDTRY.

  WHEN 4. " Syntaxfehler
    WRITE: / msg.
  WHEN 8. " Laufzeitfehler
    WRITE: / sid.
  WHEN OTHERS.
    MESSAGE 'Unbekannter Fehler.' TYPE 'I'.
ENDCASE.

Weiterführende Infos: Link