‎2006 Aug 22 3:41 PM
Hi ,
I need to create object dynamically for a class.eg when i loop thru internal table i need to create an object per pass of the loop and no of entries in itab can be known at runtime only
Any clues
Regards
Swatantra
‎2006 Aug 22 3:46 PM
Check this sample program, where it is creating a number of objects and appending them to a object list.
report zrich_0001.
types: begin of telements,
element(30) type c,
value(30) type c,
end of telements.
*---------------------------------------------------------------------*
* CLASS lcl_element DEFINITION
*---------------------------------------------------------------------*
class lcl_element definition.
public section.
data: ielements type table of telements,
xelements type telements.
methods: constructor importing im_elements type telements,
write_out.
endclass.
*---------------------------------------------------------------------*
* CLASS lcl_element IMPLEMENTATION
*---------------------------------------------------------------------*
class lcl_element implementation.
method constructor.
append im_elements to ielements.
endmethod.
method write_out.
loop at ielements into xelements.
write:/ xelements-element, xelements-value.
endloop.
endmethod.
endclass.
data: itab type table of telements with header line.
data: r_element type ref to lcl_element.
data: r_elementlist type table of ref to lcl_element.
start-of-selection.
* Create the initial list of elements.
itab-element = 'ELEMENTA'.
itab-value = 'Val_A'.
append itab.
itab-element = 'ELEMENTB'.
itab-value = 'Val_B'.
append itab.
itab-element = 'ELEMENTC'.
itab-value = 'Val_C'.
append itab.
* Create instances of the element object
* and add to the list
loop at itab .
create object r_element
exporting
im_elements = itab.
append r_element to r_elementlist.
endloop.
* loop at the list and write out the element objects.
* Notice that the r_elementlist is an internal table
* which contains 3 objects. Those three objects each
* contain 1 internal table with one record each.
loop at r_elementlist into r_element.
call method r_element->write_out.
endloop.
Regards,
Rich Heilman
‎2006 Aug 22 3:50 PM
Hello Swatantra
The number of entries in your itab is not relevant. The question is: What does "dynamically" mean?
Does it mean that you have to create instances of different classes depending on the values in your itab entry? Or are all instances you want to create of the same class?
In the first case you obviously have to define IF conditions or CASE/ENDCASE and then call the constructor of the appropriate class. You could store these different instances in an itab whose lines are of
TYPE REF TO object.In the latter case you can store the instances in an itab whose lines are of
TYPE REF TO <specific class>.Regards
Uwe