Skip to Content
0
Former Member
Jul 07, 2009 at 09:53 AM

Inherited static method to return instance of sub-class

627 Views

Hi,

I am working with NetWeaver 7.01.

Since ABAP Objects does not allow multiple constructors, I have defined a static method CREATE_FROM_SY_MSG_VARIABLES on a parent exception class, let's call it ZCX_GENERAL_FAULT, that creates an instance of the exception class where the textid is built from the system message variables.

METHOD create_from_sy_msg_variables.

  DATA:
     ls_textid TYPE scx_t100key.

* Build the text ID from the system message variables...
  ...

* Return the exception back via returning parameter RESULT
  CREATE OBJECT result
    EXPORTING
      textid = ls_textid.

ENDMETHOD.

I would like to then have this general exception sub-classed to get more specific exceptions thrown in the application logic. In the following example, both exception classes ZCX_INVALID_FORMAT and ZCX_MISSING_DATA are sub-classes of ZCX_GENERAL_FAULT.

  DATA:
    lo_exception TYPE REF TO zcx_general_fault.

  CALL FUNCTION '...'
    EXPORTING
      ...
    EXCEPTIONS
      invalid_format = 1
      missing_data  = 2.

  CASE sy-subrc.
    WHEN 1.  lo_exception = zcx_invalid_format=>create_from_sy_msg_variables( ).
    WHEN 2.  lo_exception = zcx_missing_data=>create_from_sy_msg_variables( ).
  ENDCASE.

  IF lo_exception IS BOUND.
    RAISE EXCEPTION lo_exception.
  ENDIF.

The problem with this approach is of course that method CREATE_FROM_SY_MSG_VARIABLES is creating an instance of ZCX_GENERAL_FAULT, not one of the sub-classes, whereas what I really want are instances of the sub-classes.

Does anyone know of a way to do this with ABAP Objects? The only approach I can think of, given that static methods cannot be re-defined nor can exception constructors be changed, is to pass the desired exception class name through - which is just awful.

METHOD create_from_sy_msg_variables.

  ...

  CREATE OBJECT result TYPE (x_exception_class)
    EXPORTING
      textid = ls_textid.

ENDMETHOD.

lo_exception = zcx_invalid_format=>create_from_sy_msg_variables( 'ZCX_INVALID_FORMAT' ).

Incidentally, it would be so much nicer if ABAP let classes (not just instances of classes) be passed around as data types so that we didn't have to pass them as text strings...

Kind regards,

Scott