Dirty Assignment of Local Variables in ABAP

1464-ppt

Dirty assignment is a technique we all use sometimes. Imagine that the ABAP program ZPROG1 makes a call to ZCLASS=>METHOD1. If METHOD1 needs to access a global variable within ZPROG1, the following trick can be used:

ASSIGN ‘(ZPROG1)GV_SAMPLE’ TO <lv_dirty>.

<lv_dirty> = 5.

This code will change the value of the global variable GV_SAMPLE within ZPROG1. Although this operation is highly insecure and may cause instabilities, it is a dire technique needed at times.

So far so good. It works fine on global variables. But what about local variables? What if your method needs to access a local variable; in a form, for instance? Check the following case:

REPORT zprog1. 

FORM form1.

  DATA lv_local TYPE i.

  lv_local = 5.

  ZCLASS=>METHOD1( ). 

ENDFORM.

Imagine that you need to access lv_local from within METHOD1. Assigning ‘(ZPROG1)LV_LOCAL’ doesn’t work because lv_local is not a global variable.

Well, here is the trick. Create an enhancement in FORM1 where you send the data reference of LV_LOCAL to ZCLASS.

REPORT zprog1.

FORM form1.

“””””””””” ENHANCEMENT

  FIELD-SYMBOLS <lv_dirty> TYPE i.

  ASSIGN (‘lv_local’) TO <lv_dirty>.
 
  ZCLASS=>SET_REF_OF_LV_LOCAL( iv_local_ref = REF#( <lv_dirty> ) ).

“”””””””””

  DATA lv_local TYPE i.

  lv_local = 5.

  ZCLASS=>METHOD1( ).

ENDFORM.

Please note that you can’t assign LV_LOCAL directly because at the point of enhancement, it is not defined yet. But you can assign it dynamically as (‘LV_LOCAL’).

The imaginary method ZCLASS=>SET_REF_OF_LV_LOCAL will store the reference somewhere within the class:

METHOD set_ref_of_lv_local.

  gr_local = iv_local_ref.

ENDMETHOD.

At this point, ZCLASS=>METHOD1 can access the local variable easily.

METHOD method1.

  FIELD-SYMBOLS <lv_dirty> TYPE i.

  ASSIGN gr_local->* TO <lv_dirty>.

  ADD 1 TO <lv_dirty>.

ENDMETHOD.

Neat, eh?

Advertisement

Posted

in

,

by

Tags:

Comments

One response to “Dirty Assignment of Local Variables in ABAP”

  1. Rosdorfer Avatar
    Rosdorfer

    Thanks — exactly what I was looking for!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s