SAP ABAP CLASES

From SapWiki

CLASS-METHODS

The CLASS-METHODS statement declares a static method meth. For the name meth, the naming conventions apply.

With the class component selector (=>), static methods can be used independently of objects. In static methods, the static components of the class or its superclasses can be accessed only if the component selector is not used.

REPORT ytest_clases.
CLASS cl_gui DEFINITION.
  PUBLIC SECTION.
    CLASS-METHODS gui_download IMPORTING i_filename TYPE string
                                         i_data_tab TYPE STANDARD TABLE.

ENDCLASS.

CLASS cl_gui IMPLEMENTATION.
  METHOD gui_download.
    CALL FUNCTION 'GUI_DOWNLOAD'
      EXPORTING
        filename                = i_filename
      TABLES
        data_tab                = i_data_tab
*       FIELDNAMES              =
      EXCEPTIONS
        file_write_error        = 1
        no_batch                = 2
        gui_refuse_filetransfer = 3
        invalid_type            = 4
        no_authority            = 5
        unknown_error           = 6
        header_not_allowed      = 7
        separator_not_allowed   = 8
        filesize_not_allowed    = 9
        header_too_long         = 10
        dp_error_create         = 11
        dp_error_send           = 12
        dp_error_write          = 13
        unknown_dp_error        = 14
        access_denied           = 15
        dp_out_of_memory        = 16
        disk_full               = 17
        dp_timeout              = 18
        file_not_found          = 19
        dataprovider_exception  = 20
        control_flush_error     = 21
        OTHERS                  = 22.
    IF sy-subrc <> 0.
* Implement suitable error handling here
    ENDIF.

  ENDMETHOD.

ENDCLASS.

DATA gt_t001 TYPE STANDARD TABLE OF t001.

START-OF-SELECTION.

  SELECT * INTO TABLE gt_t001 FROM t001 UP TO 10 ROWS.

  cl_gui=>gui_download( EXPORTING i_filename = 'c:\temp\ytest_t001.txt'
                                  i_data_tab = gt_t001 ).

REDEFINITION

*----------------------------------------------------------------------*
*       CLASS smart DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_smart DEFINITION ABSTRACT.
  PUBLIC SECTION.
    METHODS set_parameters IMPORTING i_form               TYPE tdsfname
                                     i_control_parameters TYPE ssfctrlop
                                     i_output_options     TYPE ssfcompop.

    METHODS get_otf EXPORTING e_otf TYPE tt_itcoo.
    METHODS get_errortab EXPORTING e_errortab TYPE tsferror.

*smartforms related
    DATA: func_module_name   TYPE rs38l_fnam,
          control_parameters TYPE ssfctrlop,
          output_options     TYPE ssfcompop,
          job_output_info    TYPE ssfcrescl,
          otf                TYPE tt_itcoo,
          errortab           TYPE tsferror.
*   data: pa_form type      tdsfname .
*  private section.
ENDCLASS.                    "smart DEFINITION

CLASS cl_smart_usuarios DEFINITION INHERITING FROM cl_smart.
  PUBLIC SECTION.
    METHODS print EXPORTING e_subrc TYPE sy-subrc.
    METHODs get_errortab REDEFINITION.

ENDCLASS.                    "smart DEFINITION
*----------------------------------------------------------------------*
*       CLASS smart IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS cl_smart IMPLEMENTATION.
  METHOD set_parameters.
*   pa_form  = i_form.
* determine the name of the generated function module for the SMartform
    CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
      EXPORTING
        formname           = i_form
      IMPORTING
        fm_name            = func_module_name
      EXCEPTIONS
        no_form            = 1
        no_function_module = 2
        OTHERS             = 3.
    control_parameters = i_control_parameters.
    output_options     = i_output_options.
  ENDMETHOD.                    "set_parameters

  METHOD get_otf.
    e_otf[] = otf[].
  ENDMETHOD.

  METHOD get_errortab.
    e_errortab[] = errortab[].
  ENDMETHOD.
ENDCLASS.                    "smart IMPLEMENTATION
CLASS cl_smart_usuarios IMPLEMENTATION.
  METHOD print.
* call the generated function module of the form
    CALL FUNCTION func_module_name
      EXPORTING
        control_parameters = control_parameters
        output_options     = output_options
*       user_settings      = space
      IMPORTING
        job_output_info    = job_output_info
      EXCEPTIONS
        formatting_error   = 1
        internal_error     = 2
        send_error         = 3
        user_canceled      = 4
        my_exception       = 5
        OTHERS             = 6.
    e_subrc = sy-subrc.
    IF sy-subrc <> 0.
* Implement suitable error handling here
*     Transfer SF errors to internal table

      CALL FUNCTION 'SSF_READ_ERRORS'
        IMPORTING
          errortab = errortab.
    ENDIF.
    otf[]  = job_output_info-otfdata[].
  ENDMETHOD.                    "print

  METHOD get_errortab.
    e_errortab[] = errortab[].
  ENDMETHOD.
ENDCLASS.                    "smart_usuarios IMPLEMENTATION

CONSTRUCTOR & EXCEPTIONS

*&---------------------------------------------------------------------*
*& Report  YTEST_SOLICITUDES
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*

REPORT ytest_solicitudes.

CLASS cl_sol DEFINITION.
  PUBLIC SECTION.
    METHODS: constructor IMPORTING  i_iddocumento TYPE zidocumento
                         EXCEPTIONS sol_no_existe,
      aprobar EXPORTING e_subrc   TYPE sy-subrc
                        e_mensaje TYPE string.

    DATA gt_sol TYPE STANDARD TABLE OF zhr_solicitudes.

ENDCLASS.

CLASS cl_sol IMPLEMENTATION.
  METHOD constructor.
    SELECT * INTO TABLE gt_sol FROM zhr_solicitudes WHERE iddocumento = i_iddocumento.
    IF sy-subrc <> 0.
      RAISE sol_no_existe.
    ENDIF.

  ENDMETHOD.

  METHOD aprobar.
    LOOP AT gt_sol INTO DATA(ls_sol)
           WHERE subty <> '0904'.
    ENDLOOP.
    IF sy-subrc <> 0.
      e_subrc = 4.
      e_mensaje = 'Solicitud de vacaciones que desea aprobar no existe.'.
      RETURN.
    ENDIF.

*---- update Registro
    ls_sol-status_solicitud = '02'.
    UPDATE zhr_solicitudes FROM ls_sol.
    COMMIT WORK.

    e_subrc = sy-subrc.
    IF sy-subrc = 0.
      e_mensaje = 'Solicitud Aprobada con éxito'.
    ELSE.
      e_mensaje = 'Error al Aprobar solicitud'.
    ENDIF.
  ENDMETHOD.

ENDCLASS.

DATA g_sol TYPE REF TO cl_sol.

PARAMETERS p_id TYPE zidocumento.


START-OF-SELECTION.
  CREATE OBJECT g_sol
    EXPORTING
      i_iddocumento = p_id
    EXCEPTIONS
      sol_no_existe = 1.
  IF sy-subrc <> 0.
    WRITE:/ |Sol { p_id } no existe|.
    RETURN.
  ENDIF.

  g_sol->aprobar( IMPORTING e_subrc = DATA(l_subrc)
                            e_mensaje = DATA(l_mensaje)
                ).

  WRITE:/ l_mensaje.

FRIENDS

REPORT ytest_interface.

INTERFACE i1.
  DATA    a1 TYPE string.
  METHODS m1.
  EVENTS  e1 EXPORTING VALUE(p1) TYPE string.
ENDINTERFACE.

CLASS c1 DEFINITION.
  PUBLIC SECTION.
    INTERFACES i1.
ENDCLASS.

CLASS c1 IMPLEMENTATION.
  METHOD i1~m1.
    RAISE EVENT i1~e1 EXPORTING p1 = i1~a1.
  ENDMETHOD.
ENDCLASS.


CLASS c2 DEFINITION FRIENDS i1.
  PRIVATE SECTION.
    DATA a1(100) VALUE 'hola'.

ENDCLASS.

CLASS c3 DEFINITION.
  PUBLIC SECTION.
    INTERFACES i1.
    METHODS m3.

ENDCLASS.

CLASS c3 IMPLEMENTATION.
  METHOD m3.
    DATA lo_2 TYPE REF TO c2.
    CREATE OBJECT lo_2.
    WRITE:/ lo_2->a1. "puede acceder al dato protegido de c2.
  ENDMETHOD.

  METHOD i1~m1.
    RAISE EVENT i1~e1 EXPORTING p1 = i1~a1.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.

  DATA g_c2 TYPE REF TO c2.
  DATA g_c3 TYPE REF TO c3.

  CREATE OBJECT g_c2.
  CREATE OBJECT g_c3.

*write:/ g_c2->a1.  "acceso no permitido

  g_c3->m3( ).  "Hola

EXCEPTION CLASSES y NEW

Creating Exception Classes

Exception classes can be defined globally in Class Builder or locally in a program. The names of global exception classes are prefixed with CX_ or, in the case of exception classes created in customer systems, YCX_ or ZCX_. There is a set of predefined global exception classes, such as those prefixed with CX_SY_, whose exceptions are raised in exception situations in the runtime environment.

All exception classes inherit the following instance methods from CX_ROOT:

GET_TEXT and GET_LONGTEXT return the exception text (short text and long text) as return values of type string. These methods are defined in the interface IF_MESSAGE implemented in CX_ROOT and can be addressed using the identically named alias name for the class. GET_SOURCE_POSITION returns the program name, the name of the include program if applicable, and the line number of the statement that raised the exception. All exception classes inherit the following instance attributes from CX_ROOT:

TEXTID of type SCX_T100KEY for a key for the database table T100 or of the type SOTR_CONC for a key for OTR (Online Text Repository) (that defines the exception text). This is normally set by the constructor and evaluated using GET_TEXT. PREVIOUS of reference type CX_ROOT, which can contain a reference to a previous exception. This is normally set by the constructor. IS_RESUMABLE of type ABAP_BOOL, which is used in a CATCH block or CLEANUP block to show whether the exception is resumable, that is whether a CATCH block can be exited using RESUME. For global exception classes, Class Builder generates a non-modifiable instance constructor that has optional input parameters for all non-private attributes and that sets these attributes to the value of the input parameters. The ID of the required exception text can be passed to TEXTID. In the case of local exception classes, there are no special rules for the instance constructor.

Notes

Instances of exception classes are generally created when exceptions are raised, but can also be instantiated using CREATE OBJECT. The instance constructor of an exception class should not raise any exceptions. However, if an exception is raised in the instance constructor after an exception was raised during instantiation of the exception class, and the exception cannot be handled there, this or (if propagation is unsuccessful) the exception CX_SY_NO_HANDLER replaces the exception originally raised. Additional methods and attributes can be defined in exception classes, for example to transport additional information about an error situation to the handler. The user-defined attributes should be read-only (READ-ONLY).

Ejemplo 01

  • Crear clase de excepción YCX_SOLICITUDES (trn. SE24)

Clase superior: CX_STATIC_CHECK

Creac.instancia: Público (2)

Crear atributo ID_SOL como instance public tipo: string, Desc: ID solicitud

crear texto ID_NO_EXISTE con clase de mensajes 0K nro. 000 y atributo 1 = ID_SOL

REPORT ytest_solicitudes.

CLASS cl_sol DEFINITION.
  PUBLIC SECTION.
    METHODS: constructor IMPORTING i_iddocumento TYPE zidocumento
                         RAISING   ycx_solicitudes,
      aprobar EXPORTING e_subrc   TYPE sy-subrc
                        e_mensaje TYPE string.

    DATA gt_sol TYPE STANDARD TABLE OF zhr_solicitudes.

ENDCLASS.

CLASS cl_sol IMPLEMENTATION.
  METHOD constructor.
    SELECT * INTO TABLE gt_sol FROM zhr_solicitudes WHERE iddocumento = i_iddocumento.
    IF sy-subrc <> 0.
      RAISE EXCEPTION TYPE ycx_solicitudes EXPORTING textid = ycx_solicitudes=>id_no_existe
            id_sol = |No existe solicitud { i_iddocumento }|.
    ENDIF.

  ENDMETHOD.

  METHOD aprobar.
    LOOP AT gt_sol INTO DATA(ls_sol)
           WHERE subty <> '0904'.
    ENDLOOP.
    IF sy-subrc <> 0.
      e_subrc = 4.
      e_mensaje = 'Solicitud de vacaciones que desea aprobar no existe.'.
      RETURN.
    ENDIF.

*---- update Registro
    ls_sol-status_solicitud = '02'.
    UPDATE zhr_solicitudes FROM ls_sol.
    COMMIT WORK.

    e_subrc = sy-subrc.
    IF sy-subrc = 0.
      e_mensaje = 'Solicitud Aprobada con éxito'.
    ELSE.
      e_mensaje = 'Error al Aprobar solicitud'.
    ENDIF.
  ENDMETHOD.

ENDCLASS.

DATA g_sol TYPE REF TO cl_sol.
DATA g_error TYPE REF TO ycx_solicitudes.

PARAMETERS p_id TYPE zidocumento.

START-OF-SELECTION.

  TRY.
      DATA(g_sol2) = NEW cl_sol( i_iddocumento = p_id ).
    CATCH ycx_solicitudes INTO g_error.
      DATA(l_message) = g_error->get_text( ).
      WRITE:/ l_message.
      RETURN.
  ENDTRY.

  g_sol2->aprobar( IMPORTING e_subrc = DATA(l_subrc)
                          e_mensaje = DATA(l_mensaje)
               ).

  WRITE:/ l_mensaje.

Ejemplo 02

Equivalente a ejemplo 01 pero con la clase de excepción definida en el programa

REPORT ytest_solicitudes.
**************************************************************************
*   Public section of class.                                             *
**************************************************************************
CLASS ycx_solicitudes_2 DEFINITION INHERITING FROM cx_static_check.
  PUBLIC SECTION.

    INTERFACES if_t100_message .

    CONSTANTS: BEGIN OF id_no_existe,
                 msgid TYPE symsgid VALUE '0K',
                 msgno TYPE symsgno VALUE '000',
                 attr1 TYPE scx_attrname VALUE 'ID_SOL',
                 attr2 TYPE scx_attrname VALUE '',
                 attr3 TYPE scx_attrname VALUE '',
                 attr4 TYPE scx_attrname VALUE '',
               END OF id_no_existe .
    DATA id_sol TYPE string .

    METHODS constructor
      IMPORTING
        textid   LIKE if_t100_message=>t100key OPTIONAL
        previous LIKE previous OPTIONAL
        id_sol   TYPE string OPTIONAL .

ENDCLASS.

CLASS ycx_solicitudes_2 IMPLEMENTATION.
  METHOD constructor.
    CALL METHOD super->constructor
      EXPORTING
        previous = previous.
    me->id_sol = id_sol .
    CLEAR me->textid.
    IF textid IS INITIAL.
      if_t100_message~t100key = if_t100_message=>default_textid.
    ELSE.
      if_t100_message~t100key = textid.
    ENDIF.
  ENDMETHOD.
ENDCLASS.

CLASS cl_sol DEFINITION.
  PUBLIC SECTION.
    METHODS: constructor IMPORTING i_iddocumento TYPE zidocumento
                         RAISING   ycx_solicitudes_2,
      aprobar EXPORTING e_subrc   TYPE sy-subrc
                        e_mensaje TYPE string.

    DATA gt_sol TYPE STANDARD TABLE OF zhr_solicitudes.

ENDCLASS.

CLASS cl_sol IMPLEMENTATION.
  METHOD constructor.
    SELECT * INTO TABLE gt_sol FROM zhr_solicitudes WHERE iddocumento = i_iddocumento.
    IF sy-subrc <> 0.
      RAISE EXCEPTION TYPE ycx_solicitudes_2
        EXPORTING
          textid = ycx_solicitudes_2=>id_no_existe
          id_sol = |No existe solicitud { i_iddocumento }|.
    ENDIF.

  ENDMETHOD.

  METHOD aprobar.
    LOOP AT gt_sol INTO DATA(ls_sol)
           WHERE subty <> '0904'.
    ENDLOOP.
    IF sy-subrc <> 0.
      e_subrc = 4.
      e_mensaje = 'Solicitud de vacaciones que desea aprobar no existe.'.
      RETURN.
    ENDIF.

*---- update Registro
    ls_sol-status_solicitud = '02'.
    UPDATE zhr_solicitudes FROM ls_sol.
    COMMIT WORK.

    e_subrc = sy-subrc.
    IF sy-subrc = 0.
      e_mensaje = 'Solicitud Aprobada con éxito'.
    ELSE.
      e_mensaje = 'Error al Aprobar solicitud'.
    ENDIF.
  ENDMETHOD.

ENDCLASS.

DATA g_sol TYPE REF TO cl_sol.
DATA g_error TYPE REF TO ycx_solicitudes.

PARAMETERS p_id TYPE zidocumento.

START-OF-SELECTION.

    TRY.
      DATA(g_sol3) = NEW cl_sol( i_iddocumento = p_id ).
    CATCH ycx_solicitudes_2 INTO data(g_error_2).
      DATA(l_message_2) = g_error_2->get_text( ).
      WRITE:/ l_message_2.
      RETURN.
  ENDTRY.
  
  g_sol3->aprobar( IMPORTING e_subrc = DATA(l_subrc)
                          e_mensaje = DATA(l_mensaje)
               ).

  WRITE:/ l_mensaje.

RECEIVING/RETURNING

REPORT ytest_clases.

CLASS cl_empleado DEFINITION.
  PUBLIC SECTION.
    CLASS-METHODS: get_nombre IMPORTING  i_pernr         TYPE p0002-pernr
                                         i_begda         TYPE p0002-begda DEFAULT sy-datum
                                         i_endda         TYPE p0002-endda DEFAULT sy-datum
                              RETURNING  VALUE(r_nombre) TYPE string
                              EXCEPTIONS empleado_no_existe
                                         nombre_no_existe,

                   get_nombre_2 IMPORTING i_pernr         TYPE p0002-pernr
                                          i_begda         TYPE p0002-begda DEFAULT sy-datum
                                          i_endda         TYPE p0002-endda DEFAULT sy-datum
                              RETURNING VALUE(r_nombre) TYPE string.

ENDCLASS.

CLASS cl_empleado IMPLEMENTATION.
  METHOD get_nombre.
    DATA lt_p0002 TYPE TABLE OF p0002.

    CLEAR r_nombre.

    IF i_pernr IS INITIAL.
      RETURN.
    ENDIF.

    CALL FUNCTION 'HR_READ_INFOTYPE'
      EXPORTING
        pernr           = i_pernr
        infty           = '0002'
      TABLES
        infty_tab       = lt_p0002
      EXCEPTIONS
        infty_not_found = 1
        OTHERS          = 2.
    IF sy-subrc <> 0.
* Implement suitable error handling here
      RAISE empleado_no_existe.
    ENDIF.

    LOOP AT lt_p0002 INTO DATA(ls_p0002) WHERE begda <= i_endda AND
                           endda >= i_begda.
    ENDLOOP.
    IF sy-subrc = 0.
      r_nombre = |{ ls_p0002-vorna } { ls_p0002-nachn } { ls_p0002-name2 }|.
      CONDENSE r_nombre.
    ELSE.
      RAISE nombre_no_existe.
    ENDIF.

  ENDMETHOD.

  METHOD get_nombre_2.
    DATA lt_p0002 TYPE TABLE OF p0002.

    CLEAR r_nombre.

    IF i_pernr IS INITIAL.
      RETURN.
    ENDIF.

    CALL FUNCTION 'HR_READ_INFOTYPE'
      EXPORTING
        pernr           = i_pernr
        infty           = '0002'
      TABLES
        infty_tab       = lt_p0002
      EXCEPTIONS
        infty_not_found = 1
        OTHERS          = 2.
    IF sy-subrc <> 0.
* Implement suitable error handling here
      RETURN.
    ENDIF.

    LOOP AT lt_p0002 INTO DATA(ls_p0002) WHERE begda <= i_endda AND
                           endda >= i_begda.
    ENDLOOP.
    IF sy-subrc = 0.
      r_nombre = |{ ls_p0002-vorna } { ls_p0002-nachn } { ls_p0002-name2 }|.
      CONDENSE r_nombre.
    ENDIF.

  ENDMETHOD.

ENDCLASS.

PARAMETERS p_pernr TYPE p0002-pernr.

START-OF-SELECTION.

  CALL METHOD cl_empleado=>get_nombre
    EXPORTING
      i_pernr            = p_pernr
    RECEIVING
      r_nombre           = DATA(l_nombre)
    EXCEPTIONS
      empleado_no_existe = 1
      nombre_no_existe   = 2.

  WRITE:/ l_nombre.
  WRITE:/ sy-subrc.

  l_nombre = cl_empleado=>get_nombre_2( i_pernr = p_pernr ).
  WRITE:/ l_nombre.
  WRITE:/ sy-subrc.