We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Creating a new object from a list choice

blarouche
blarouche asked
on
Medium Priority
209 Views
Last Modified: 2010-03-31
Hi Experts


Here is my question :

From a list I get one or more selection that goes into a sortedList.
From that list I have to create a new object that correspond to the class name.

for example my first choice is SwingTrader and that choice correspond to the creation of a SwingTrader object...
 
Here is the code :


private class OKListener implements ActionListener {
          public void actionPerformed(ActionEvent e) {
          
                  
                  xxxxxxxx st = new xxxxxx(destListModel,pointer);
                  
                } else{
                
                }

What do I have to do to create that object automatically


Thank you
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016

Commented:
You can map String to class

Map<String, Class> stringToClass = new HashMap<String, Class>();
stringToClass.put("StringTrader", a.b.c.StringTrader.class);


Object x = stringToClass.get("StringTrader").newInstance();

Author

Commented:
I don't know how to figure that out

The next choice for example could be "swing"


When the user click on the OK button now I have to create an object from the swing class.

What would be my code in the actionPerformed button?




CERTIFIED EXPERT
Top Expert 2016

Commented:
>>What would be my code in the actionPerformed button?


Object x = stringToClass.get((String)list.getSelectedObject()).newInstance();

Author

Commented:
CEHJ


there is something I don't understand because I have to include parameters in the creation of my object.

SwingTrader has to be replaced by the selection but I have to include destListModel and pointer parameters

SwingTrader st = new SwingTrader(destListModel,pointer);


Author

Commented:
I don't want to have to write code like that :


if (system == "SwingTrader"){                            
            SwingTrader st = new SwingTrader(destListModel,pointer);
                } else{}          
                
if (system == "Swing"){                            
            Swing st = new Swing(destListModel,pointer);
                } else{}          

etc ............
Java Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
you can store the Class objects themselves in the list
then to

Class clazz = (Class) list.getSelectedValue();

> I have to include parameters in the creation of my object.

Are the parameters the same?
if so use something like:

Constructor ctor = clazz.getDeclaredConstructor(new Class[] { ListModel.class, Object.class}) ;
Object o = ctor.newInstance(new Object[] {estListModel, pointer});

If the parameters are different, then I'd suggest storing a factory in the list where the factory handles the object creation.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2016

Commented:
Make the SwingTrader a bean - give it an empty ctor and give it setListModel and setPointer methods
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> Make the SwingTrader a bean - give it an empty ctor and give it setListModel and setPointer methods

unnecessary, they can be passed in the ctor as I've shown above
u could even store the Constructor in the list to save you some work.

You would use a custom list renderer to comtrol what is actually displayed in the list

CERTIFIED EXPERT
Top Expert 2016

Commented:
No need to use reflection. Most Java classes should be designed as beans anyway as they will increase their compatibility with other APIs thereby

Author

Commented:
objects

here is my modified code

private class OKListener implements ActionListener {
          public void actionPerformed(ActionEvent e) {
                
                Class clazz = (Class) system;
                
                Constructor ctor = clazz.getDeclaredConstructor(new Class[] { ListModel.class, Object.class});
                Object o = ctor.newInstance(new Object[] {destListModel, pointer});
                
}


Now system is a String coming from a user selection.

I have the following error :
Cannot cast from String to Class
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
use the getSelectedValue() to get Object from list

eg.

Class clazz = (Class) list.getSelectedValue();
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>Now system is a String coming from a user selection.


Object x = stringToClass.get(system).newInstance();
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
If you don't want to store the Class objects in the list then use:

Class clazz = Class.forName(system);

Though more efficient to store Class (or Constructor's) in list

Author

Commented:
I've got a number of unhandled exception

What would be my catch blocks

for example
catch(ClassNotFoundException ect){}
catch(NoSuchMethodException  et){}
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> What would be my catch blocks

just:

catch (Exception ex) {

if you don't have specific actions to take for different exceptions
and if you do add exception blocks for the exceptions you want to handle seperately before it

Author

Commented:
Sorry

I am coming back to you because I had to work on somethig else

It still doesn't work. When I run the code nothing happens. When I call the constructor for class SwingTrader I should be executing a method.

Here is my  code :

private class okbuttonListener implements ActionListener {

          public void actionPerformed( ActionEvent e )
          {
              LinkedList list = new LinkedList();  
              for(int i = 0; i < destList.getModel().getSize(); i++) {
              list.add(destList.getModel().getElementAt(i));                                  
                }
              
                selectedsystem = txt.getText();
                
                
                final LoadXMLConfiguration chemin;
          chemin = new LoadXMLConfiguration("C:/XML/chemin.xml",true);
          String Lechemin = chemin.getDriver();
                        
          try{
          Class clazz = Class.forName(selectedsystem);
          Constructor ctor = clazz.getDeclaredConstructor(new Class[] { String.class, String.class, LinkedList.class, Object.class});
           Object o = ctor.newInstance(new Object[]      {Lechemin+"src/SteadFast/systems/SwingTrader.xml","C:/XML/chemin.xml",list, pointer});
             }
              catch(Exception ex){}


           dispose();                
          }
       }



Do you see something from that code that is wrong ?
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
>               catch(Exception ex){}

change that so u know if something goes wrong

              catch(Exception ex) { ex.printStackTrace(); }

Make sure selectedsystem is the fully qualified class name (ie. also contains package).

Author

Commented:
Here is the result when I include the package name :


java.lang.NoSuchMethodException: systems.SwingTrader.<init>(java.lang.String, java.lang.String, java.util.LinkedList, java.lang.Object)
      at java.lang.Class.getConstructor0(Unknown Source)
      at java.lang.Class.getDeclaredConstructor(Unknown Source)
      at GUI.SystemSelection$okbuttonListener.actionPerformed(SystemSelection.java:372)
      at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
      at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
      at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
      at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
      at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
      at java.awt.Component.processMouseEvent(Unknown Source)
      at javax.swing.JComponent.processMouseEvent(Unknown Source)
      at java.awt.Component.processEvent(Unknown Source)
      at java.awt.Container.processEvent(Unknown Source)
      at java.awt.Component.dispatchEventImpl(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Window.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.EventQueue.dispatchEvent(Unknown Source)
      at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.run(Unknown Source)

Author

Commented:
I am increasing the points because I am stuck with this problem.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
thats saying the class does not have a ctor that takes those args, what ctors does SwingTrader have?

Author

Commented:
When I run this code :

Constructor con[]= Class.forName("systems.SwingTrader").getDeclaredConstructor();
 for (int x=0;x<con.length;x++)
System.out.println("Constructor "+x+" = "+con[x]);
}
catch(Exception ex){ ex.printStackTrace();}

I get :

Constructor 0 = public systems.SwingTrader()
Constructor 1 = public systems.SwingTrader(java.lang.String,java.lang.String)
Constructor 2 = public systems.SwingTrader(java.lang.String,java.lang.String,java.util.LinkedList,quotes.DBQuotes)


I have three constructors in my SwingTrader class :
Here they are :

  /**
     * Constructor 1
     */
    public SwingTrader() {
        this.systemName         = "Break out of n days";
        this.systemDescription  = "Break Out system)";
        this.systemAuthor       = "Bernard Larouche";
        this.showInfo();
     
    }
      
    /**
     * Constructor 2
     * @param configFile
     */
    public SwingTrader(String configFile, String xmldirectory) {
        super(configFile,xmldirectory);
        // TODO Auto-generated constructor stub
    }
      
   
        /**
     * Constructor 3
     * @param configFile
     */
    public SwingTrader(String Config,String xmldir,LinkedList list, DBQuotes pointer) {
        super(Config,xmldir,list,pointer);
       
    }


and Here my three constructors from the super class ASystem :

    /**
     * Constructor
     */
    public ASystem(){};
   

   
    /**
     * Constructor
     * @param symbol
     */
    public ASystem(String configFile, String xmldirectory){
            way = new LoadXMLConfiguration("C:/XML/chemin.xml",true);
            String theway = way.getDriver();
        conf = new LoadXMLConfiguration(configFile,true);
        this.configurationFile = configFile;
        dir = new LoadXMLConfiguration(xmldirectory,true);
        this.directory = xmldirectory;
        // for each symbol in configuration file run this system
        for (int i=0;i<conf.getSymbols().length;i++){
            this.symbol = conf.getSymbols()[i];
            confcost = new LoadXMLConfiguration(theway+"jars/config/commissions/"+symbol+"Spec.xml",true);
            this.symbolminmove = confcost.getMinMove();
            executeSystem();
        }
       
    }

   
    public ASystem(String configFile,String xmldirectory,LinkedList list, DBQuotes pointer){
          
          
          this.LList = list;
          this.pointer = pointer;
          way = new LoadXMLConfiguration("C:/XML/chemin.xml",true);
            String theway = way.getDriver();
            conf = new LoadXMLConfiguration(configFile,true);
        this.configurationFile = configFile;
            dir = new LoadXMLConfiguration(xmldirectory,true);
        this.directory = xmldirectory;
            
        // for each symbol in configuration file run this system
        for (int i=0;i<LList.size();i++){
            this.symbol = (String)LList.get(i);
            confcost = new LoadXMLConfiguration(theway+"jars/config/commissions/"+symbol+"Spec.xml",true);
            this.symbolminmove = confcost.getMinMove();
            executeSystem();
        }
     
    }














Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
>           Constructor ctor = clazz.getDeclaredConstructor(new Class[] { String.class, String.class, LinkedList.class, Object.class});

should be

          Constructor ctor = clazz.getDeclaredConstructor(new Class[] { String.class, String.class, LinkedList.class, DBQuotes.class});

Author

Commented:
objects

You are the best !!


Thank you
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.