Check Variable is Object Reference

By | Last Updated on April 5, 2013 | 2,459

You can always use IS BOUND to check if the Variable is instantiated or not. But, if you want to check if any variable is referring to a class or in other words, variable is declared with TYPE REF TO, you use this technique leveraging CASTING.

Check Variable is Object Reference

 
" Your main variables, which you want to check if its
" an object or not
DATA: lo_alv   TYPE REF TO cl_salv_table,
      lo_data  TYPE REF TO data.
FIELD-SYMBOLS: <fs_any> TYPE ANY.
*
*
DATA: lo_temp_obj TYPE REF TO object,
      lo_root     TYPE REF TO cx_root.
* Object reference
TRY .
    lo_temp_obj ?= lo_alv.
    WRITE: /'Is an Object'.
  CATCH cx_root INTO lo_root.
    WRITE: /'NOT an object'.
ENDTRY.
*
* Data reference
"Complier wont allow it to cast DATA ref to OBJECT ref
"so you know at complie time itself if variable is object
"or not
"lo_temp_obj ?= lo_data.
*
* Dynamic Data reference
GET REFERENCE OF sy-subrc INTO lo_data.
ASSIGN lo_data->* TO <fs_any>.
TRY .
    lo_temp_obj ?= <fs_any>.
    WRITE: /'Is an Object'.
  CATCH cx_root INTO lo_root.
    WRITE: /'NOT an object'.
ENDTRY.
*
* Check if the object is instantiated or not
IF lo_alv IS BOUND.
  WRITE: /'Object is instantiated'.
ELSE.
  WRITE: /'Object is not instantited'.
ENDIF.
 

Reference Link


Do you have a Code Snippet which you want to share, Submit Code Snippet here

Share It!

Don't miss an Update

Get notified of the new post, right into your inbox

Naimesh Patel{272 articles}

I'm SAP ABAP Consultant for more than a decade. I like to experiment with ABAP especially OO. I have been SDN Top Contributor.
Follow :

Explore all of his 272 articles.

Load comments

Comments on this Post are now closed. If you have something important to share, you can always contact me.