ABAP OO, Creating object dynamically

Hi everybody,
     I’m currently working on some Abap OO examples. Everything is working ok except for the following: Creating objects dynamically.
This is what I’d like to do:
Lets say we obtain a bunch of sales orders using a simple select statement and place them in an internal table. For each entry in our internal table, I’d like to generate a new sales order object. This salesorder object is a simple class with a constructor with an Id and some other attributes.
When this is done, I’d like to append every object to a new object, say basket, so that this basket contains something like an internal table within each record a reference to the salesorder. Is this easy to do? I’m using the example that is described in the sap guide (create object pointer type (class_name) but it looks to me that you still have to declare the reference variables before you can create the object.
Hmm, I think Java is better suited for a job like this.
Hope you can help,
Cheers and Best wishes
Laurens Steffers
The Netherlands.

Hi,
Its not all that difficult in ABAP as well. The following code is based on Chapter 5, Listing 5.20 from book ABAP Objects.
What you need is an internal table of type <your sales object> e.g.
DATA: BEGIN OF obj_sales_order
        sales_order_no LIKE <sales_order_no_type>,
        <...>,
        objref TYPE REF TO <SALES_ORDER_CLASS>
      END OF obj_sales_order,
      reftab LIKE SORTED TABLES OF obj_sales_order
                  WITH UNIQUE KEY sales_order_no
                                  <other key attributes>.
Now all you need to do is to do a SELECT...ENDSELECT loop, and:
SELECT ...
obj_sales_order-sales_order_no = <selection result>
obj_sales_order-<other key attr> = <selection result>
READ TABLE reftab INTO obj_sales_order
                  FROM obj_sales_order.
IF sy-subrc <> 0.
  CREATE OBJECT obj_sales_order-objref
         EXPORTING ...
         EXCEPTIONS ...
  IF sy-subrc <> 0.
    MESSAGE ...
    CONTINUE.
  ELSE.
    INSERT obj_sales_order INTO TABLE reftab.
  ENDIF.
ENDIF.
CALL METHOD obj_sales_order-objref-><method>.
ENDSELECT.
Hope this help.
Regards

Similar Messages

  • How to create objects dynamically (with dynamic # of parameters)

    I need to create a set of objects based on a definition from an XML file (obtained from the server) and add them to my scene.
    I understand how to create the object using getDefinitionByName (and the limitations regarding classes needing to be referenced to be loaded into the SWF).
    But some objects require parameters for the constructor, and some don't. The XML can easily pass in the required parameter information, but I can't figure out how to create a new object with a dynamic set of arguments (something akin to using the Function.call(obj, argsArray) method.
    For example, I need something like this to work:
    var mc=new (getDefinitionByName(str) as Class).call(thisNewThing, argsArray)
    Currently this is as far as I can get:
    var mc=new (getDefinitionByName(str) as Class)(static, list, of, arguments)
    Thoughts?

    I think what Dave is asking is a bit different.
    He's wanting to know how to invoke the constructor of an object dynamically (when he only knows the # of constructor arguments at runtime).
    This class I know will do it but seems to be a hack:
    http://code.google.com/p/jsinterface/source/browse/trunk/source/core/aw/utils/ClassUtils.a s?spec=svn12&r=12
    See the 'call' method, which first counts the # of arguments then invokes one of 'n' construction methods based on the number of constructor args.
    I've yet to find a clean AS3 way of doing things ala 'call' though.
    -Corey

  • Creating objects dynamically

    can we create objects(instance of a class in other class) with repect to time
    that is i want to create an object for every 30 sec can we do that
    iam new to java can anyone help me

    There are serveral ways, but creating objects is meaningless without doing something with them.
    Thread.sleep() is the simplest call to wait an interval like 30 seconds or you can use a Timer object to call a piece of code periodically.
    But I have the feeling that you're coming at the thing from the wrong end.

  • Hi in abap ooprs create object

    after the declaration and implementation of the class
    we create an object with reference to the above class is the creation of an object nothing but the creation of an instance
    like
    class even definition.
    public **
    endclass.
    class ** implementation
    endclass.
    data ** ref to even.
    create ** .
    call method **->even.
    now in the above cove we created an object with reference to the class
    is the creation of the onject nothing but creation of an instance for that class.

    Refer this sample code for ALV
    INCLUDE <icon>.
    * Predefine a local class for event handling to allow the
    * declaration of a reference variable before the class is defined.
    CLASS lcl_event_receiver DEFINITION DEFERRED.
    CLASS cl_gui_container DEFINITION LOAD.
    DATA : o_alvgrid          TYPE REF TO cl_gui_alv_grid,
           o_dockingcontainer TYPE REF TO cl_gui_docking_container,
           o_eventreceiver    TYPE REF TO lcl_event_receiver.
    CLASS lcl_event_receiver DEFINITION.
    *   event receiver definitions for ALV actions
      PUBLIC SECTION.
        CLASS-METHODS:
    * Status bar
           handle_user_command
            FOR EVENT user_command OF cl_gui_alv_grid
                IMPORTING e_ucomm.
    ENDCLASS.
    CLASS lcl_event_receiver IMPLEMENTATION.
      METHOD handle_user_command.
    * In event handler method for event USER_COMMAND: Query your
    *   function codes defined in step 2 and react accordingly.
        CASE e_ucomm.
          WHEN 'FCODE'.
            CALL METHOD o_alvgrid->get_selected_rows
              IMPORTING
                et_index_rows = i_selected_rows
    *            ET_ROW_NO     =
            IF i_selected_rows[] IS INITIAL.
              MESSAGE i153 WITH text-009.
              LEAVE LIST-PROCESSING.
            ENDIF.
            CLEAR: w_reviewed_mat.
    *        w_reviewed_mat-reviewed = c_x.
    *        w_reviewed_mat-reviewedby = sy-uname.
    *        w_reviewed_mat-reviewedon = sy-datum.
            LOOP AT i_selected_rows INTO w_selected_rows.
              READ TABLE i_output INTO w_output INDEX w_selected_rows-index.
              IF sy-subrc EQ 0.
                w_reviewed_mat-matnr = w_output-matnr.
              ENDIF.
              APPEND w_reviewed_mat TO i_reviewed_mat.
              CLEAR: w_reviewed_mat-matnr.
            ENDLOOP.
    *        MODIFY zzcs_mat FROM TABLE i_reviewed_mat.
          WHEN OTHERS.
        ENDCASE.
      ENDMETHOD.
    In PBO after creating container
    SET HANDLER o_eventreceiver->handle_user_command  FOR o_Alvgrid.

  • Create ABAP object dynamically

    Is it possible to create objects dynamically?
    so that the name of the class is set via parameters and also the variables and which class is the superclass?
    something like:
    fieldsymbols: <a> type any.
    data: data_object type ref to object.
    create new class type data_object.
    data_object-name = 'dynamic'.
    data_object-subclass = 'superclass'.
    create object <a> like class 'dynamic'
    <a>-(method of superclass)(   ) etc...
    It is not ABAP code, but i hope you know what i mean?
    Kindly hear from you!
    Anton Pierhagen

    You can use dynamic reference to instantiate your objects.
    Like:
    data: lo_ref type ref to object.
    create object lo_Ref type ('ZCLASS').
    call method lo_ref->('METH_1').
    But problem in this design would be that your class & method name is hardcoded and it would be only checked at runtime, not at the design time. To overcome, this you can use the [Factory Method Design pattern|http://help-abap.zevolving.com/2011/10/abap-objects-design-patterns-factory-method/].
    Regards,
    Naimesh Patel

  • Creating object class dynamically

    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

    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

  • Access dynamically created objects

    Hello!
    I create some images dynamically by running a for from 1 to a
    variable preset. The pictures have the IDs image1, image2 ...
    ("image"+i). I then add other properties.
    Problem is for each I need an onMouseOverHandler thant will
    swap the image with another.
    I can get the target image with event.currentTarget.id. But I
    cannot set it's properties with this["image"+i].source (I need to
    change the ones up to that as well) and I cannot access it with
    this.getChildByName("image"+i).source either.
    What am I doing wrong please?

    "M*A*S*H 4077" <[email protected]> wrote in
    message
    news:go74q6$fbb$[email protected]..
    > Hello!
    >
    > I create some images dynamically by running a for from 1
    to a variable
    > preset.
    > The pictures have the IDs image1, image2 ...
    ("image"+i). I then add other
    > properties.
    >
    > Problem is for each I need an onMouseOverHandler thant
    will swap the image
    > with another.
    > I can get the target image with event.currentTarget.id.
    But I cannot set
    > it's
    > properties with this["image"+i].source (I need to change
    the ones up to
    > that as
    > well) and I cannot access it with
    this.getChildByName("image"+i).source
    > either.
    >
    > What am I doing wrong please?
    ID is about as useful as your appendix when you create
    objects dynamically.
    The event.target property will contain a reference to your
    image.

  • ABAP OBJECTS: Dynamic Create object

    Hi folks!
    I have a problem... I need to create a dynamic type object with:
    <b>DATA: my_instance TYPE REF TO class1.
    CREATE OBJECT my_instance TYPE (class2).</b>
    <i>* where class1 is a superclass of class2.</i>
    When I do:
    <b>my_instance ?= m_parent.</b>
    <i>* where m_parent is an instance of class1</i>
    My problem is when I want to access to an attribute of the class2, the compiler says that it cannot find the attribute <i>(this is OK, because the attribute is only in the class2).</i>
    My question:
    Is there anyway to access to an atribute of second class when is not in the first class? (i don't want to create the attribute as an attribute of the first class).
    Thanx!!!!

    Hi David,
    When you do the debugging, you are dealing with run-time - i.e., the program is now running and you are just interrupting it at each statement to examine the program state. You will reach the point where the object is already created. That is why you can see all those attributes. But when you comiple, the program is not yet <i>running</i>, so the attributes will be unknown because of the dynamic type specification.
    I think you will have to redesign the program logic. As i had already said in my earlier post, it is not proper to have the attributes specified statically while the class itself is specified dynamically.
    Your situation is somewhat similar to -
    DATA ITAB TYPE TABLE OF SPFLI.
    PERFORM TEST TABLES ITAB.
    FORM TEST TABLES ITAB.
      LOOP AT ITAB.
        WRITE: / ITAB-CARRID.
      ENDLOOP.
    ENDFORM.
    Hope the point is clear.
    Regards,
    Anand Mandalika.

  • Instantiate a ABAP Object Dynamically

    I would like to get some guidance on Dynamically instantiating objects within ABAP.
    I have worked with Java.  Within Java I am able to instantiate a Java object through the use Class.forName (see example below):
    className = "com.vz.it.cleansheet.eFine.db.query.WBRDMTWKCNDATABEAN";
    try {
         singleton = (Object) Class.forName(classname).newInstance();
         } catch (ClassNotFoundException cnf) {
                   System.out.println("SingletonRegistry - Couldn't find class "}
    Is there a similar procedure in ABAP OO to enable dynamically instantiating a ABAP object?
    I would appreciate any advice.
    Thanks,
    Rick

    You can instantiate an object dynamically,  here is a sample program.  Notice that we are creating an object passed on what class is named in the selection screen.
    report zrich_0001.
    *       CLASS lcl_car DEFINITION
    class lcl_car definition.
      public section.
        data: car type string.
    endclass.
    *       CLASS lcl_car IMPLEMENTATION
    class lcl_car implementation.
    endclass.
    *       CLASS lcl_truck DEFINITION
    class lcl_truck definition.
      public section.
        data: truck type string.
    endclass.
    *       CLASS lcl_truck IMPLEMENTATION
    class lcl_truck implementation.
    endclass.
    data: r  type ref to object.
    parameters: p_class(20) type c default 'LCL_TRUCK'.
    start-of-selection.
      create object r type (p_class).
      check sy-subrc = 0.
    Regards,
    Rich Heilman

  • Creating and Binding View Objects dynamically : Oracle Jdeveloper 11g

    Hello,
    We are trying to create and bind view objects dynamically to adf data visualization components.
    The view object is a result of multiple tables.
    We are using Oracle JDeveloper 11g Technical Preview. ( can't upgrade to TP2 or TP3 now).
    We have found this : http://radio.weblogs.com/0118231/stories/2003/07/15/creatingUpdateableMultientityViewObjectDefinitionsDynamically.html on our search for the same.
    The sample application however, is in 10g , hence required migration.
    Also, it was a standalone application with the TestClient.java having a main() method.
    Our requirement is for Web Application; we use Adf+jsf .
    Guidance of any sort is very much appreciated.
    Thanks in advance.
    -Anil Golla

    Hi,
    there also exist a forum for JDeveloper 11: JDeveloper and OC4J 11g Technology Preview
    What you are trying todo is not trivial because you need to not only dynamically create the VO, you would also dynamically need to create the binding meta data for it (assuming you use ADF). Not sure if the API to modify the binding is public, so posting it on the JDeveloper 11 forum bears a glimpse of hope for an answer
    In JDeveloper 10.1.3 you can't do this
    Frank

  • ABAP OO:  Duplication of selected data in created objects?

    I am new to ABAP OO and I have a conceptual question/concern that I cannot resolve.  Can someone explain what I am missing?
    I would think that selecting and storing (in internal tables) a large amount of data from many related database tables and, at the same time, creating and storing objects from this same data would unnecessarily consume a huge amount of memory.  To avoid this problem, it seems that the selected data and created objects should not be stored in internal tables simultaneously.
    Does this concern make sense?  If so, how is this problem best handled?
    Does it make sense to delete the corresponding data once the objects are created (to free memory)?
    Or does it make sense to keep the data and only temporarily create objects as needed?
    Thanks.

    Hello Matt
    The approach you describe is to select data first and the feed the object instances with them. <b>Why not let the object instances do the data selection themselves?</b>
    I will give you an example what I mean.
    (1) Lets assume I want to write an application that allows to deal with cost center hierarchies. On the selection screen you can choose one or many cost center hierarchies.
    (2) Using the selection criteria I would select all cost center hierarchies but without any details (just the key values).
    (3) Next I would loop over the cost center hierarchies and create a cost center hierarchy instance (a class you have to define yourself) for each key value. The CONSTRUCTOR of this class will have an IMPORTING parameter like <i>id_kostl_hier</i>.
    (4) In the CONSTRUCTOR method I first check if the cost center hierarchy exists (if not raise an exception-class based exception) and then do the selection of the hierarchy details (e.g. the cost centers).
    (5) The instances are collected in an itab of the "frame" application.
    Using this approach you will have little duplication of data within your application. Furthermore, if you really have to deal with huge amounts of data then you could read them only on demand (like in tree controls where the sub-nodes usually are read when the parent node is expanded).
    Hope I could give you some fresh insights into this exciting topic.
    Regards
      Uwe

  • Use Granfeldts Create Object to create dynamic groups

    Trying to use Sorens Granfeldts, Create Object WF activity to create dynamic groups.
    In a standard function evaluator activity I generate the Filter as [//WorkflowData/Filter]
    The "string" I set it to is:
    &lt;Filter xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot; Dialect=&quot;http://schemas.microsoft.com/2006/11/XPathFilterDialect&quot; xmlns=&quot;http://schemas.xmlsoap.org/ws/2004/09/enumeration&quot;&gt;/Person[ObjectID
    = /*[ObjectID = &apos;8dfcb5e8-ff01-400c-8ca7-2a0002d2d2d4&apos;]/ComputedMember]&lt;/Filter&gt;
    In the CreateObject activity I then just have [//WorkflowData/Filter],Filter among the initial values.
    The creation works if I remove this attribute so the rest of the attributes seems to be working.
    The creation fails however end I get the error below in the Forefront Identity Manager event log.
    System.NullReferenceException: Object reference not set to an instance of an object.
       at Microsoft.ResourceManagement.WFActivities.Resolver.GetDisplayStringFromGuid(Guid id, String[] expansionAttributes)
       at Microsoft.ResourceManagement.WFActivities.Resolver.ReplaceGuidWithTemplatedString(Match m)
       at System.Text.RegularExpressions.RegexReplacement.Replace(MatchEvaluator evaluator, Regex regex, String input, Int32 count, Int32 startat)
       at System.Text.RegularExpressions.Regex.Replace(String input, MatchEvaluator evaluator)
       at Microsoft.ResourceManagement.WFActivities.Resolver.GetStringAttributeValue(Object attribute)
       at Microsoft.ResourceManagement.WFActivities.Resolver.ResolveEvaluatorWithoutAntiXSS(String match, ResolverOptions resolveOptions)
       at Microsoft.ResourceManagement.WFActivities.Resolver.ResolveEvaluatorForWithAntiXSS(String match, ResolverOptions resolveOptions)
       at Microsoft.ResourceManagement.WFActivities.Resolver.ReplaceMatches(String input, Boolean useAntiXssEncoding, ResolverOptions resolveOptions)
       at Microsoft.ResourceManagement.Workflow.Hosting.ResolverEvaluationServiceImpl.ResolveLookupGrammar(Guid requestId, Guid targetId, Guid actorId, Dictionary`2 workflowDictionary, Boolean encodeForHTML, String expression)
       at Microsoft.ResourceManagement.Workflow.Activities.ResolveGrammarActivity.Execute(ActivityExecutionContext executionContext)
       at System.Workflow.ComponentModel.ActivityExecutor`1.Execute(T activity, ActivityExecutionContext executionContext)
       at System.Workflow.ComponentModel.ActivityExecutor`1.Execute(Activity activity, ActivityExecutionContext executionContext)
       at System.Workflow.ComponentModel.ActivityExecutorOperation.Run(IWorkflowCoreRuntime workflowCoreRuntime)
       at System.Workflow.Runtime.Scheduler.Run()
    Have anyone used this WF activity to create dynamic groups and can tell how to set the Filter?

    Hey Kent!
    I did the same thing, with Søren`s Create Object WF. I did it like this on the filter part:
    <Filter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Dialect="http://schemas.microsoft.com/2006/11/XPathFilterDialect" xmlns="http://schemas.xmlsoap.org/ws/2004/09/enumeration">/Person[(Department = '[//Target/ObjectID]')]</Filter>,Filter
    The whole thing looks like this:
    (I use Function evaluator to generate a AccountName for groups based on a clean version of DisplayName).
    [//Target/DisplayName],DisplayName
    SEC_[//WorkFlowData/CleanAccountName],AccountName
    [//Target/Manager],Owner
    Security,Type
    DOMAIN_STRING,Domain
    Universal,Scope
    [//Target/DisplayName]_SecGroup,Description
    [//Target/Manager],DisplayedOwner
    None,MembershipAddWorkflow
    True,MembershipLocked
    [//Target/CleanAccountName],MailNickname
    <Filter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Dialect="http://schemas.microsoft.com/2006/11/XPathFilterDialect" xmlns="http://schemas.xmlsoap.org/ws/2004/09/enumeration">/Person[(Department = '[//Target/ObjectID]')]</Filter>,Filter
    Regards, Remi www.iamblogg.com

  • How to create a lock object dynamically ?

    Hi all,
    I have a report with  a selection screen having one parameter in which the user can put a table name(Custom table) and some other paremeters.Based on these parameters I need to delete records from table put on the selection screen.Before deeting I need to lock the table. As beforehand I dont know the table name how can I create lock object dynamically lock my table ?
    Please suggest some idea...

    Hi,
    check below link
    lock objects
    http://help.sap.com/erp2005_ehp_03/helpdata/EN/7b/f9813712f7434be10000009b38f8cf/frameset.htm
    Regards,
    Madhu

  • Create Multiple dynamic Node in Web Dynpro Abap

    Hi Friends,
          I need your help.My object is to create Multiple dynamic dropdown UI element.I am able to create this dynamic Dropdown element. But i need to assign default different values to this dropdown elements.So i created dynamic nodes for each dropdown and created attribute with same name as that of value table.
       My issue is its giving me error as : -
    Lower-Level Node with Name ZDCN_BRD_STATUS.ME Does Not Exist
    Help me to rectify this error..
    Regards,
    Santosh

    Hi,
    This information is not enough for anybody to help you. Write more in detail about your code and where exactly in the code this error is coming.
    One trial experiment can be that you split your problem into two or more level.
    Create several nodes in your context with attribute and sample data.
    Create Dynamic UI (DDBI) and Bind these attributes to your DDBI.
    When it works perfectly, then tryout how to create the Node and attribute dynamically. This way you are not making it too complex to solve this problem.

  • How to Create View Object Dynamically

    Hi,
    I hav a requirement to create a view object dynamically.
    can anybody plz help me.
    Thanks
    Nan:)

    Hi,
    oracle.apps.fnd.framework.server.OAApplicationModuleImpl amImpl = (oracle.apps.fnd.framework.server.OAApplicationModuleImpl)AM;
    OAViewDef viewDef = AM.getOADBTransaction().createViewDef();
    viewDef.setSql(sql.toString());
    viewDef.setExpertMode(true);
    //viewDef.setViewObjectClass("oracle.apps.fnd.framework.server.OAViewObjectImpl");
    //viewDef.setViewRowClass("oracle.apps.fnd.framework.server.OAViewRowImpl");
    oracle.jbo.ViewObject oaviewobject=amImpl.createViewObject("TableVO",viewDef);
    if(oaviewobject !=null)
    TableBean.setViewUsageName("oaviewobject");
    TableBean.setViewAttributeName("TncId");
    Thanks
    Nani:)

Maybe you are looking for

  • ViewExpiredException issue with session invalidate on IE9

    Hi guys, I have posted this on the ADF forum as well as I'm not sure of the root cause is JHeadstart related or not - but I thought I would check also here to see if anyone else has encountered this ... I'm using JDeveloper 11.1.1.6 (JHeadstart 11.1.

  • Is there a Battery Doctor that works for iPad2?

    I've tried two different "Battery Doctor" apps for my iPad 2 (iOS 6.1.3).  One free app from Chine (web site is in Chinese, so I can't read it for support), one from RTF Technologies ($3.00).   The problem is that neither one will register that a ful

  • Load balancing with JSP

    Anyone and everyone, When configuring load balancing with Weblogic clusters, does load balancing take effect for all services or just EJB and RMI? Or another way of saying the same thing, can I setup weighted load balancing for the JSP engines across

  • Backup is not running thru brtools

    Hi All I am trying to run the backup thru brtool utility and am getting below mentioned error. BR0051I BRBACKUP 7.00 (32) BR0055I Start of database backup: benqcbwx.ffd 2014-04-14 15.20.31 BR0484I BRBACKUP log file: /oracle/RJH/sapbackup/benqcbwx.ffd

  • Firefox and horizontal scrollbars

    Hi, When using Firefox 3 to view wide APEX pages, I don't get the horizontal scrollbars. Is this a known issue? Yoni