Dynamically instantiating objects using string name

Hello to all.
This is probably an easy question, but I am wondering how I can dynamically create instances of an object in a loop using a string variable as the name.
The idea here is this:
               while (someBooleanVariable) {
                    int count = 1;
String objectName = "myObject" + count;
                    myObject objectName = new myObject; // How do I pass the objectName String variable as a name?
                    count++;
               } // End while
Of course this doesn't work - incompatible types, but the idea is that the code would create "myObject1," "myObject2," "myObject3," "myObject4," etc as long as someBooleanVariable = true using the objectName String variable.
I am new to this and appreciate any help and ideas.
Thanks!

BigDaddyLoveHandles wrote:
There's been this outbreak of people wanting to dynamically name their variables -- is this some sort of scripting disease?It's always been around. Shoot, I remember suffering from it when I first started out, because it seems so, hm I dunno, necessary at the time. Eventually the newbie (me) realizes that the variable "name" means nothing, that reference is everything.
... and then I discovered maps, and names were useful again. :o)

Similar Messages

  • Dynamic class loading from String name

    Hello all,
    I have a question for dynamic class loading:
    If I have a String variable that represents a class name, how can i use it to make dynamically an object of the class tha the string variable represents?
    For example i have a string like this
    String classname="String";
    Using this i want to make a new String object .
    Can anyone tell me how can i do this(example plz)?

    I have worked out the code and this works fine:
    import java.lang.*;
    class dynamictestname{
         public dynamictestname() {
        public static Class test(String objname){
             try{
             Class theClass = Class.forName(objname);
                 return theClass;
            } catch (ClassNotFoundException e)
                throw new NoClassDefFoundError (e.getMessage());
         public static void main (String [] args){
              String classname="java.lang.String";
              Class thisClass=dynamictestname.test(classname);
              try{
              Object instance = thisClass.newInstance();
              }catch(InstantiationException e){
              }catch(IllegalAccessException ie){
    }The new problem i 've faced is that i can't instatiate a new object by the class i have created.I saw some examples with use of the java.lang.reflect but this class i used with user created classes which have methods that the user wants to run dynamically.
    I just want to make an object from the class and give it a value.
    For example if the object i have created with the
    Object instance = thisClass.newInstance();is an object of java.lang.String class
    how can i do something like this below dynamically from instance object :
    String x="TEST ";
    Thanks for the help..

  • Instantiating object using Class.forName()

    What is the difference between instantiating using Class.forName() method and instantiating using the new operator?

    The difference is that you can use the new operator to instantiate an object, but you can't do it using Class.forName().
    But seriously folks...
    Presumably you're talking about Class.newInstance()--which often appears right on the heels of Class.forName().
    New gives you compile-time checks you don't get with Class.forName(). If it compiles with new, then you know the constructor in question exists on the class in question.
    With Class.newInstance() (and it's cousin (also called newInstance, I think) in the Constructor class), you can't be sure until you actually execute it whether that constructor even exists.
    New requires you to know the class at compile time. NewInstance lets you defer the specific class until runtime.
    New is simpler and more direct.
    (Did I just do your homwork for you? Hope not.)

  • Creating Objects with String name

    How can i create an object, but just having the name as String?
    Like, instead of creating like JInternalFrame obj = new MyInternalFrame(), do it like JInternalFrame obj = createObject("MyInternalFrame") ( i just gave createObject as example, ignore it)...
    Does anyone knows how to do it? Because i have several windows, and by clicking, i dont want to be with a lot of if clauses checking each one to se wich one is the ritgh class to call...
    Tks,
    Bruno

    You need the Class class in package java.lang, specifically class (static) method forName() and instance method newInstance():
    JInternalFrame obj =
        (JInternalFrame) Class.forName("MyInternalFrame").newInstance();

  • Dynamic creating SAPBobsCOM objects using reflection

    Hi All,
    I'm writing a tool (C#) for SBO for exporting object (oItems, oBanks etc.) to XML files. And I have a problem how to dynamically create object by it's string description. I'm trying to create it using System.Reflection, but cant't find right way to create it.
    It must be like that, but it doesn't work:
               Type  sboObject = System.Type.GetType("SAPbobsCOM.Items, Interop.SAPbobsCOM", true, true);
               object ibaseObject = Activator.CreateInstance(sboObject);
    Any ideas?)

    Hi
    I've writen this code for instantiating DI API objects using .NET reflection
            private object getObjectBo(int tipo) //tipo: integer representing the object type
                object o = null;
                try
                    Type tipoComp = kernel.Company.GetType(); //Type SAPbobsCOM.Company
                    MethodInfo info = tipoComp.GetMethod("GetBusinessObject");
                    object[] parametros = new object[1]; //Parameters of GetBusinessObject
                    object tipoObj = Enum.ToObject(typeof(SAPbobsCOM.BoObjectTypes), tipo);
                    parametros[0] = tipoObj;
                    o = info.Invoke(kernel.Company, parametros);  //Calling GetBusinessObject           
                catch (Exception ex)
                    kernel.Application.MessageBox(ex.Message, 0, "", "", "");
                return o;
    The object returned is COM object (not managed code) then we can't use .NET reflection directly for exploring its methods and attributes .. I think we should use C++ and IDispatch interface, but i don't know how do this yet.
    Hope it helps.
    Regards

  • Using Reflectors To Dynamically Call Objects

    Hi,
    I have a Class that has two methods and each method takes two parameters (1st Method Takes Integers / 2nd Takes Double) and returns and Integer. I want to invoke these methods using Java.Reflectors so I could Do dynamic instantiations and method calling.
    I have generated an experimental test harness class as given below....
    *========================================================*
    public static void main(String[] args) {
            try {
                // Getting a Class available in the Pachage to Class Instance
                Class cls = Class.forName("testreflection.ClassMethods");
                // Instance of Current Class
                Main o_Obj = new Main();
                // Get the declared methods in the Class instand "cls"
                Method[] m_Methods = cls.getDeclaredMethods();
                for(int i=0; i<m_Methods.length; i++){
                    // Obtain the parameter types of each method
                    Type[] typ_MethodParameterTypes = m_Methods.getGenericParameterTypes();
    // Int array for Random Integer inputs as Parameters
    int[] i_Prameter = new int[typ_MethodParameterTypes.length];
    Random r_RandomInt = new Random();
    for(int j=0; j<typ_MethodParameterTypes.length;j++){
    // Just Display the Input Type
    System.out.println(typ_MethodParameterTypes[j].toString());
    i_Prameter[j]=r_RandomInt.nextInt();
    //Display the Input value to the above type
    System.out.println(i_Prameter[j]);
    // Trying to invke the 1st Method in the Mehtod array
    m_Methods[0].invoke(o_Obj, i_Prameter);
    } catch (IllegalArgumentException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    //} catch (InstantiationException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    *==============================================================*
    THen I am getting the following error.... Can any one help me...
    int
    -1680302169
    int
    -1149051431
    Mar 30, 2011 11:02:53 AM testreflection.Main main
    SEVERE: null
    java.lang.IllegalArgumentException: object is not an instance of declaring class
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at testreflection.Main.main(Main.java:52)
    Edited by: EJP on 30/03/2011 12:17: added the code tags. Please use them.
    Edited by: JLearner on Mar 29, 2011 6:18 PM
    Edited by: JLearner on Mar 29, 2011 6:20 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    EJP wrote:
    java.lang.IllegalArgumentException: wrong number of argumentsSo you are calling the method with the wrong number of arguments.
    The error messages are quite clear, in both cases.Here is the Method that I am Calling in the Class "ClassMethods"
    public int getAddition(int i_Number1,int i_Number2){
            int i_Total = i_Number1+i_Number2;
            return i_Total;
        }This method Takes two Integer values and returns an Integer.
    I am calling this method using java reflections as below.
    // Get the declared methods in the Class instand "cls"
                Method[] m_Methods = cls.getDeclaredMethods();
                for(int i=0; i<m_Methods.length; i++){
                    // Obtain the parameter types of each method
                    Type[] typ_MethodParameterTypes = m_Methods.getGenericParameterTypes();
    // Int array for Random Integer inputs as Parameters
    int[] i_Prameter = new int[typ_MethodParameterTypes.length];
    Random r_RandomInt = new Random();
    for(int j=0; j<typ_MethodParameterTypes.length;j++){
    // Just Display the Input Type
    System.out.println(typ_MethodParameterTypes[j].toString());
    i_Prameter[j]=r_RandomInt.nextInt();
    //Display the Input value to the above type
    // Currently hold two parameter values
    System.out.println(i_Prameter[j]);
    // Trying to invke the 1st Method in the Mehtod array
    Object obj = cls.newInstance();
    m_Methods[0].setAccessible(true);
    // invoking with instance of Method own class and parameters (two integer parameters in an array )
    m_Methods[0].invoke(obj, i_Prameter);

  • Can't access object using "id" or "name" if created with actionscript

    How can you register an instance of an object with actionscript so that it's id or name value is accessible?
    I included a simple example where a Button is created using mxml and in the same way it is created using actionscript.  The actionscript object is inaccessible using it's "id" and "name" property.
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
                   creationComplete="application1_creationCompleteHandler(event)">
        <fx:Script>
            <![CDATA[
                import mx.events.FlexEvent;
                protected function application1_creationCompleteHandler(event:FlexEvent):void
                    import spark.components.Button;
                    var asBtn:Button = new Button();
                    asBtn.label = "actionscript";
                    asBtn.x = 200;
                    asBtn.id = "asButton";
                    asBtn.name = "asButtonName";
                    addElement(asBtn);
                    trace("mxmlButton="+this["mxmlButton"].label); // returns: mxml  label
                    //trace("mxmlButton="+this["asButton"].label); // returns runtime error: ReferenceError: Error #1069: Property asButton not found on TestId and there is no default value.
                    //trace("mxmlButton="+this["asButtonName"].label); // returns runtime error: ReferenceError: Error #1069: Property asButtonName not found on TestId and there is no default value.
            ]]>
        </fx:Script>
        <s:Button
            id="mxmlButton"
            label="mxml label"
            alpha="0.8"/>
    </s:Application>

    Hi Dan,
    It is a very rare occurrence when I miss not being able to access an object (object property, really) using the ["name"] notation for objects created using actionscript.
    In MXML the compiler is conveniently adding an attribute to the class with the same name as the id, so you can conveniently refer to it using the [] notation. While we explicitly specify an application container to use, the MXML compiler creates a custom container which is a derivative of the base container and to that it adds properties for the children declared in MXML. I guess it also effectively calls "addElement" for us when  the container is being constructed.
    Your example assumes that using "addElement" to add the button to the application container is the same as declaring a variable (ie property ). It isn't, so there's no point in looking for an property of the name "as3Button" using the [] notation, because it doesn't exist. The container is managing a collection of children in it's display list and that's not the same as being accessible as properties of the container.
    Generally speaking, accessing properties using the ["name"] syntax isn't necessary.
    Paul
    [edit: you may wonder why "addElement" doesn't conveniently also add the "id" attribute to be an property of the container class. Unfortunately, it can't because the container class would need to be dynamic and it's not. A further complication would be that adding properties at runtime would invite naming clashes at runtime with associated mayhem. MXML can do this because the compiler generates the class and can trap name duplication at compile time.
    Great question, BTW.
    -last edit changed my "attributes" to be "properties" in line with Adobe's terminology]

  • Paging issues using a dynamic view object...

    I am working on an application that uses JAG to generate JSP pages, i had the requirement to use dynamic view objects where the view object query is generated at runtime. The rest of the application is more or less the same... I used the defult functionality provided by TableScrollButtons.jsp file for paging. Now the problem im facing is that while the '>' and '<' buttons are working fine, i cant seem to navigate to the pages using the drop down...
    With the default handler, whenever i select the range the range displayed remains the same ie 1-10, 10 being the rangesize, but the rows are refreshed with values from the next page. Also, if the next page is the last and is incomplete, then the rows are pushed in from the bottom, so that the last page is always full...I tried the tuning panel in the view object edit dialogue and all settings are fine (i think)...could anyone please tell me what i am doing wrong??

    could it be because i am using a dynamic view object with dynamic bindings? i am using the preparemodel() method in the action as follows...
    protected void prepareModel(DataActionContext ctx) throws Exception {
    inferRangeBindingIfUnset(ctx);
    ctx.getBindingContainer().setEnableTokenValidation(false);
    String sql = ctx.getHttpServletRequest().getParameter("sql");
    String cost=ctx.getHttpServletRequest().getParameter("CostCostCent");
    String event=ctx.getHttpServletRequest().getParameter("event");
    if (sql != null && event == null) {
    setupDynamicQueryAndDynamicBindings(ctx,sql.substring(1),cost);
    if (retrieveOnlyCurrentPageFromDatabase()) {
    ViewObject vo = getIterForPaging(ctx).getViewObject();
    if (vo.getAccessMode() != ViewObject.RANGE_PAGING) {
    vo.setAccessMode(ViewObject.RANGE_PAGING);
    // if(event==null)
    super.prepareModel(ctx);
    ctx.getBindingContainer().setEnableTokenValidation(true);
    if (ctx.getEvents() == null || ctx.getEvents().size() ==0) {
    setPage(ctx,1);
    setLastPage(ctx,getIterForPaging(ctx).getRowSetIterator().getEstimatedRangePageCount());
    else if(event.equals("setRangeStart")) {
    setPageFromRequest(ctx);
    }

  • Dynamic Creation of Objects using Tree Control

    I am able to Create Dynamic Objets using List control in
    flex,but not able to create objects using TreeControl,currently iam
    using switch case to do that iam embedding source code please help
    me how to do that
    <?xml version="1.0" encoding="utf-8"?>
    <!--This Application Deals With How to Create Objects
    Dynamically -->
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:XML id="treeDP">
    <node label="Controls">
    <node label="Button"/>
    <node label="ComboBox"/>
    <node label="ColorPicker"/>
    <node label="Hslider"/>
    <node label="Vslider"/>
    <node label="Checkbox"/>
    </node>
    </mx:XML>
    <mx:Script>
    <![CDATA[
    import mx.core.UIComponentGlobals;
    import mx.containers.HBox;
    import mx.controls.*;
    import mx.controls.VSlider;
    import mx.controls.Button;
    import mx.controls.Alert;
    import mx.core.UIComponent;
    import mx.controls.Image;
    import mx.managers.DragManager;
    import mx.events.DragEvent;
    import mx.controls.Tree;
    import mx.core.DragSource
    import mx.core.IFlexDisplayObject;
    /*This function accepts the item as on when it is dragged
    from tree Component */
    private function ondragEnter(event:DragEvent) : void
    if (event.dragSource.hasFormat("treeItems"))
    DragManager.acceptDragDrop(Canvas(event.currentTarget));
    DragManager.showFeedback(DragManager.COPY);
    return;
    else{
    DragManager.acceptDragDrop(Canvas(event.currentTarget));
    return;
    /*This Function creates objects as the items are Dragged
    from the TreeComponent
    And Creates Objects as and When They Are Dropped on the
    Container */
    private function ondragDrop(event:DragEvent) : void
    if (event.dragSource.hasFormat("treeItems"))
    var items:Array =event.dragSource.dataForFormat("treeItems")
    as Array;
    for (var i:int = items.length - 1; i >= 0; i--)
    switch(items
    [email protected]())
    case "Button":
    var b:Button=new Button();
    b.x = event.localX;
    b.y = event.localY;
    b.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    myCanvas.addChild(b);
    break;
    case "ComboBox":
    var cb:ComboBox=new ComboBox();
    myCanvas.addChild(cb);
    cb.x = event.localX;
    cb.y = event.localY;
    cb.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    break;
    case "ColorPicker":
    var cp:ColorPicker=new ColorPicker();
    myCanvas.addChild(cp);
    cp.x = event.localX;
    cp.y = event.localY;
    cp.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    break;
    case "Vslider":
    var vs:VSlider=new VSlider();
    myCanvas.addChild(vs);
    vs.x = event.localX;
    vs.y = event.localY;
    vs.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    break;
    case "Hslider":
    var hs:HSlider=new HSlider();
    myCanvas.addChild(hs);
    hs.x = event.localX;
    hs.y = event.localY;
    hs.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    break;
    case "Checkbox":
    var check:CheckBox=new CheckBox();
    myCanvas.addChild(check);
    check.x = event.localX;
    check.y = event.localY;
    check.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    break;
    else {
    var Component:UIComponent =
    event.dragSource.dataForFormat("items") as UIComponent ;
    Component.x = event.localX;
    Component.y = event.localY;
    Component.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
    myCanvas.addChild(Component);
    /*How to move the Objects within the Container */
    public function mouseMoveHandler(event:MouseEvent):void{
    var
    dragInitiator:UIComponent=UIComponent(event.currentTarget);
    var ds:DragSource = new DragSource();
    ds.addData(dragInitiator,"items")
    DragManager.doDrag(dragInitiator, ds, event);
    ]]>
    </mx:Script>
    <mx:Tree dataProvider="{treeDP}" labelField="@label"
    dragEnabled="true" width="313" left="0" bottom="-193" top="0"/>
    <mx:Canvas id="myCanvas" dragEnter="ondragEnter(event)"
    dragDrop="ondragDrop(event)" backgroundColor="#DDDDDD"
    borderStyle="solid" left="321" right="-452" top="0"
    bottom="-194"/>
    </mx:Application>
    iwant to optimize the code in the place of switch case
    TextText

    Assuming your objects are known and what you need are simply
    variable names created by the program, try using objects as
    associative arrays:
    var asArray:Object = new Object();
    for (var n:int = 0; n < 10; n++) {
    asArray["obj" + n] = new WHAT_EVER();

  • Using variable names for object names

    Is there any way you can use a String variable to name an object? I.e., something like:
    String name = "objectName";
    \\ create an Image object named objectName
    Image (name.valueOf()) = new Image();
    This code obviously does not work, but I'm working on a map applet which uses a map composed of thousands of tiles, and then shows only a portion of the map by drawing the appropriate tiles into the window using the x/y coordinates and a nested for loop to determine which tiles to draw. However, unless I want to manually declare and then call each of these Image objects, I need to have a way to have the actual name of each image object be a reference to a variable, which I will then initalize according to the name of the tile I'm using. Does that make sense at all? Anyway, I was just wondering if anyone knows of any way to do this. Thanks.
    -Ari

    Typically this is done using a Collection, for example:
    Image[] img = new Image[100];
    for (int i=0; i<img.length;i++)
      img[i] = new Image();... Sort of thing.

  • Help, can I declare an object using a variable name

    I need to make a bunch of objects using a for loop, so I was wanting to name the object one of the variables that I read. But I basically want to know if I can do this.
         private Software makeObject(String proName, int proStock, double proPrice,String objName){
              Software objName = new Software(proName,proStock,proPrice);
              return objName;
    I want to create a Software object using the objName inputted to it. The software object holds three fields as you can see. The name, num in stock, and price. However it won't let me do this, because it says objName is a duplicate variable. Help would be appreciated

    private Software makeObject(String proName, int proStock, double proPrice,String objName){
    Software objName = new Software(proName,proStock,proPrice);
    ... it won't let me do this, because it
    says objName is a duplicate variable. Help would be
    appreciatedWell, it is duplicate. Change the name of one or the other of those variable names.

  • Problem in using table name dynamically in PL/SQL

    I tried to create a procedure to use table name dynamically and got the following error. Anything wrong with my procedure?
    NFADV>declare
      2   cnt number;
      3   cursor cur is select table_name from user_tables where table_name in ('EMP','DEPT');
      4  begin
      5   for c1 in cur
      6   loop
      7    execute immediate select count(*) into cnt from c1.table_name;
      8      dbms_output.put_line('Count is : '||cnt);
      9   end loop;
    10  end;
    11  /
    declare
    ERROR at line 1:
    ORA-06550: line 7, column 21:
    PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
    ( - + case mod new not null <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> avg
    count current exists max min prior sql stddev sum variance
    execute forall merge time timestamp interval date
    <a string literal with character set specification>
    <a number> <a single-quoted SQL string> pipe
    <an alternatively-quoted string literal with character set specification>
    <an alternatively-quo
    ORA-06550: line 8, column 5:
    PLS-00103: Encountered the symbol "DBMS_OUTPUT"
    ORA-06550: line 8, column 45:
    PLS-00103: Encountered the symbol ";" when expecting one of the following:
    . ( , * % & - + / at mod remainder rem <an identifier>
    <a double-quoted delimited-identifier> <an exponent (**)> as
    from into || multiset bulkThanks and Regards
    Kaustubh

    Hi,
    The wrong part is in execute immediate, it should be as follows:
    execute immediate ('select count(*) from '|| c1.table_name)
    into cnt
    (not tested)
    Regards
    AK

  • How to use table name dynamically in report  procedure

    Hello every body
    I want to use table name dynamically means at runtime i want to pass table name.
    I can do this by lexical parameter in main query.
    But my problem is that i want to crate new format trigger or new function that use 1 cursor in which that lexical parameter : table name is used.
    so how to do that?
    i can not use that lexical parameter it is giving error.
    please help me how to do that.

    Call a database function which you pass the lexical parameter. Then in the database function you use dynamic sql or the execute immediate option to build the SQL string.
    Return the information from this function to build your business logic on in your format trigger.
    Marcos

  • Use String Variable in New Object Creation

    Thanks to those who review and respond. I am new to Java, so please be patient with my terminoloy mistakes and fumblings. I am reading in a file and I want to create a new object based on specific field (car for example). As you will notice I grab field 8 here label sIID.
    String sIID = dts.group(8);
    BTW this regex grouping works fine. The problem is seen when I try to use the sIID variable in my new object creation process.
    DateParse sIID = new DateParse();
    My IDE is reporting "Variable sIID is already defined in the scope"
    Is this possible? The assumption is that the sIID will have different value during the processing of the file. For example, car could mean truck, sedan, etc with operators like color, number of doors, mileage, top speed, etc.

    Thanks for the reply. I have include similar and much shorter code for the sake of brevity.
    My problems are centered around the x variable/object below. Ideally this would translate to three objects PersonA, PersonB, etc that I could reference later in the code as PersonA.newname if I wanted to. Hopefully this makes sense.
    public class TestingObjects {
      public static void main(String[] argv) {
           String [] names;
           names = new String[3];
           names[0] = "PersonA";
           names[1] = "PersonB";
           names[2] = "PersonC";
           for (String x:names) {
             PN x = new PN();  // <- Problem
             x.name = x;
             x.SayName();
            System.out.println(x.newname);
    public class PN {
           String name;
           String newname;
      public String SayName() {
           newname = "Name = " + name;
           System.out.println(name);
          return newname;
    }

  • Need to get IRole object using Roles Display Name

    Hi,
    I need to get IRole object using Roles Display Name. I had the below code in EP 2004 SP12 and it works. But the same code dont work in EP 2004s SP13
    user = request.getUser();
    profile = request.getComponentContext().getProfile();     
    String strRoles = profile.getProperty("Roles");
    String strRole[] = strRoles.split(",");
    IRoleFactory roleFactory = UMFactory.getRoleFactory();
    String roleUniqueId = null;
    int i = 0;
    boolean flagRedirect = false;
    for(i = 0; i < strRole.length; i++){
         try
              com.sap.security.api.IRole role = roleFactory.getRoleByUniqueName(strRole<i>);
              roleUniqueId = role.getUniqueID();
              if(!user.isMemberOfRole(roleUniqueId, true))
                   continue;
              flagRedirect = true;                    
              break;
         catch(UMException ex)
         catch(IOException ex)
    if(!flagRedirect){
    Where property Roles will have comma separated roles display names like "com.ABC.ortho_reports,com.ABC.lawns_ortho_reports,com.ABC.executive_reports"
    Please advise.

    Thanks Mrudula for the response. Sorry for the delay in responding.
    I get UMEException with the message "Role with uniqueName com.ABC.general not found"
    But it works fine if i specify Role unique role (like pcd:portal_content/com.abc.Marketing_Workbench/com.abc.Roles/com.abc.general).
    We are in the process of upgrading Portal environment from EP6.0 SP12 to EP7.0 SP13. Above scenario works fine in the older environment.

Maybe you are looking for