Reflection in ABAP

Say you want to create an instance of a class that implements a certain interface, but you won’t know the name of the class you want to create until runtime. In Java or .NET you would have used the reflection mechanism, but can you handle this case in ABAP?
Apparently, you can.
Here’s a short code snippet showing how:



DATA: iv_classname TYPE seoclsname.
DATA: iv_interface TYPE REF TO IF_INTERFACE_NAME.
DATA: gr_error TYPE REF TO cx_dynamic_check.
DATA: gv_message TYPE string.

iv_classname = 'CL_CLASSNAME'.

TRY .
CREATE OBJECT iv_interface TYPE (iv_classname).

CATCH cx_sy_create_object_error INTO gr_error.
gv_message = gr_error->get_text( ).
WRITE :/1 gv_message.

CATCH cx_sy_dyn_call_param_missing INTO gr_error.
gv_message = gr_error->get_text( ).
WRITE :/1 gv_message.

ENDTRY.



Let’s have a look at the code.
In the first four rows, you define several variables data types.
iv_classname hold the name of the class (that’s the name which will be known only in runtime)
iob_object – a reference to an interface that the class you’ll instantiate implements.
The other two variables are for error handling purposes.
Now, you use the CREATE OBJECT ABAP statement.


CREATE OBJECT iv_interface TYPE (iv_classname).



Note that had you known the class name during compile time, you could use the following statement:


CREATE OBJECT iv_interface TYPE CLASSNAME.


The difference? No parenthesis, plus you give the class name instead of a string containing the class name.
Let’s move on. In case the class does not exist on the system you’re running (or your provided a wrong class name), you’ll get the exception CX_SY_CREATE_OBJECT_ERROR, saying that the class you’re trying to instantiate couldn’t be found. In case there are missing parameters, you will get a CX_SY_DYN_CALL_PARAM_MISSING exception. Note that in the example above no parameters were passed to the constructor, but in case there are parameter, the creation statement should look as follows.


CREATE OBJECT iv_interface TYPE (iv_classname) EXPORTING param1 = value1 param2 = value2.


You now know a little bit about dynamically instantiating objects in your code – a great way to implement dynamic and extensible factory methods!

Read more...

About This Blog

This blog contains tips, tricks, tutorial, and some of my personal experiences with the SAP ABAP language.

FEEDJIT Live Traffic Feed

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP