I have an internal table filled with the type reference for the objects I want to create, like so (first line is the header of internal table ITAB):
+==========+===============+
| OBJ_TYPE | OBJ_CLASS_REF |
+==========+===============+
| TYPE1 | ZCL_CLASS1 |
|----------|---------------|
| TYPE2 | ZCL_CLASS2 |
+----------+---------------+
What I would like to do in my program is this (I put 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 successfully do lines 5 and 6?
First of all, it's a good idea to provide an interface or an abstract superclass and have your various classes implement that interface or subclass that abstract class - this will save you a lot of unnecessary casting. So let's say you have ZIF_FOO with classes ZCL_BAR and ZCL_BAZ implementing it. The table could 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 the table like this:
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 its 30 characters won't be enough) and specify the type name as described in the online documentation of the RTTI:
ls_instance-typename = '\PROGRAM=ZMYREPORT\CLASS=LCL_MYCLASS'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With