SAP Tech Pro

SAP Technical Blog
Topprice Price Comparison

Object Oriented Programming in ABAP - Dynamic Method Calls

Object Oriented Programming in ABAP - Dynamic Method Calls

One can call methods dynamically. Following restrictions apply:-

  • Name of the method can be dynamic for static/instance method.
  • Name of the class while calling static method can be dynamic.
  • Both the name of the static method and the class containing it can be dynamic.

While doing so, it is better to use uppercase to assign the name of the class/methods to the variables( which will be used for dynamic assignment)

The following program contains class C1 with static method(STATM) and dynamic method(INSTM). The program utilizes all the syntaxes to call these static/instance methods dynamically.


REPORT zstp_oo_abap.

DATA : f(6)  TYPE c,
       g(10) TYPE c.

CLASS c1 DEFINITION.
  PUBLIC SECTION.
    CLASS-METHODS : statm .
    METHODS : instm .
ENDCLASS.

CLASS c1 IMPLEMENTATION.
  METHOD : statm .
    WRITE:/5 'I am static method'.
  ENDMETHOD.

  METHOD : instm.
    WRITE:/5 'I am instance method'.
  ENDMETHOD.
ENDCLASS.


START-OF-SELECTION.
  DATA : oref TYPE REF TO c1.
  CREATE OBJECT oref.
* Name of instance method can be dynamic
  f = 'INSTM'.
  CALL METHOD oref->(f).
* Name of static method can be dynamic
  f = 'STATM'.
  CALL METHOD oref->(f).
* Name of the class can be dynamic for static method call
  f = 'C1'.
  CALL METHOD (f)=>statm.
* Name of the method can be dynamic for static method call
  f = 'STATM'.
  CALL METHOD c1=>(f).
* Both can be dynamic for static method call
  g = 'C1'.
  CALL METHOD (g)=>(f).

Output -

image

Add comment

Before Buying, Compare Prices at Topprice.in

Topprice.in