Skip to Content
author's profile photo Former Member
Former Member

Dynamic Object Instances

In my program I want to create an unknown number of object instances at runtime from an existing class. Is there a way to dynamicallly create object instances during runtime and have access to each individual object's instance methods. I would also like to store the instances in a table of objects, but can't find the exact syntax for creating an itab or structure of object instances. I have searched for this in the forums and online, but can't seem to get anything that actually gives me exactly what I am looking for (google syndrome).

Add a comment
10|10000 characters needed characters exceeded

Assigned Tags

Related questions

1 Answer

  • Best Answer
    Posted on Dec 13, 2011 at 10:34 PM

    You can explicitly give the type while instantiating the object. If you runtime class is inherited from the super class, you can the Super class to define the variable. This way, you would get the access to all the methods / attributes at compile time which are there in the ZCL_SUPER.

    data: lo_obj type ref to zcl_super.
    data: lv_class type string.
    lv_Class = 'ZCL_SUPER_KID'.
    create object lo_obj type (lv_class).
    

    If any of the component doesn't exist in the defined class, you need to call the method dynamically. If method is not there is the object, it would result in the runtime error.

       call method lo_obj->('METH_NOT_IN_SUPER').
    

    To store them in the table, you can do something like this:

    data: LT_OBJ type standard table of ref to zcl_super.
    data:  lo_obj type ref to ZCL_SUPER.
    data: lv_class type string.
    lv_Class = 'ZCL_SUPER_KID'.
    create object lo_obj type (lv_class).
    append lo_obj to LT_OBJ.
    

    OR

    types: begin of lty_obj,
                 obj type ref to ZCL_SUPER,
               end   of lty_obj.
    data: LT_OBJ type standard table of lty_obj.
    data: lwa_obj like line of LT_OBJ.
    
    data: lv_class type string.
    lv_Class = 'ZCL_SUPER_KID'.
    create object lwa_obj-obj type (lv_class).
    append lwa_obj to LT_OBJ.
    

    Regrads,

    Naimesh Patel

    Add a comment
    10|10000 characters needed characters exceeded

Before answering

You should only submit an answer when you are proposing a solution to the poster's problem. If you want the poster to clarify the question or provide more information, please leave a comment instead, requesting additional details. When answering, please include specifics, such as step-by-step instructions, context for the solution, and links to useful resources. Also, please make sure that you answer complies with our Rules of Engagement.
You must be Logged in to submit an answer.

Up to 10 attachments (including images) can be used with a maximum of 1.0 MB each and 10.5 MB total.