How to dynamically create objects based on an internal table in ABAP?

I have an internal table populated with a reference to the type of objects I want to create, for example (the first row is the title of the internal ITAB table):

+==========+===============+ | OBJ_TYPE | OBJ_CLASS_REF | +==========+===============+ | TYPE1 | ZCL_CLASS1 | |----------|---------------| | TYPE2 | ZCL_CLASS2 | +----------+---------------+ 

What I would like to do in my program is this (I put the line numbers):

 1 LOOP AT itab 2 "Concatenate LO_ and the value of ITAB-OBJ_TYPE 3 CONCATENATE 'LO_' itab-obj_type INTO v_obj_name. 4 "Create a reference object 5 CREATE DATA (v_obj_name) TYPE REF TO itab-obj_type. 6 CREATE OBJECT (v_obj_name). 7 ENDLOOP 

How do I make lines 5 and 6?

+4
source share
1 answer

First of all, it is recommended to create an interface or an abstract superclass, and your various classes will implement this interface or subclass, that an abstract class will save you from unnecessary casting. So, let's say you have ZIF_FOO with implementations ZCL_BAR and ZCL_BAZ. Table may be

 TYPES: BEGIN OF t_line type_name TYPE seoclass, instance TYPE REF TO zif_foo, END OF t_line. DATA: lt_instances TYPE STANDARD TABLE OF t_line, ls_instance TYPE t_line. 

Then you can fill in the table as follows:

 ls_instance-type_name = 'ZCL_BAR'. " or wherever you get this value from CREATE OBJECT ls_instance-instance TYPE (ls_instance-type_name). 

If you want to use local classes, you can do the same - just use a longer type name (SEOCLASS with 30 characters will not be enough) and specify the type name as described in the RTTI online documentation:

 ls_instance-typename = '\PROGRAM=ZMYREPORT\CLASS=LCL_MYCLASS'. 
+7
source

Source: https://habr.com/ru/post/1401092/


All Articles