Link to home
Start Free TrialLog in
Avatar of blarouche
blarouche

asked on

Creating a new object from a list choice

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
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

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();
Avatar of blarouche
blarouche

ASKER

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?




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


Object x = stringToClass.get((String)list.getSelectedObject()).newInstance();
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);


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 ............
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Make the SwingTrader a bean - give it an empty ctor and give it setListModel and setPointer methods
> 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

No need to use reflection. Most Java classes should be designed as beans anyway as they will increase their compatibility with other APIs thereby
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
use the getSelectedValue() to get Object from list

eg.

Class clazz = (Class) list.getSelectedValue();
>>Now system is a String coming from a user selection.


Object x = stringToClass.get(system).newInstance();
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
I've got a number of unhandled exception

What would be my catch blocks

for example
catch(ClassNotFoundException ect){}
catch(NoSuchMethodException  et){}
> 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
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 ?
>               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).
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)
I am increasing the points because I am stuck with this problem.
thats saying the class does not have a ctor that takes those args, what ctors does SwingTrader have?
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();
        }
     
    }














>           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});
objects

You are the best !!


Thank you