Solved

Creating a new object from a list choice

Posted on 2006-11-07
23
192 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
0
Comment
Question by:blarouche
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 8
  • 5
23 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 17892113
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();
0
 

Author Comment

by:blarouche
ID: 17892182
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?




0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17892431
>>What would be my code in the actionPerformed button?


Object x = stringToClass.get((String)list.getSelectedObject()).newInstance();
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

Author Comment

by:blarouche
ID: 17892599
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);


0
 

Author Comment

by:blarouche
ID: 17892756
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 ............
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 17892889
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.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17892899
Make the SwingTrader a bean - give it an empty ctor and give it setListModel and setPointer methods
0
 
LVL 92

Expert Comment

by:objects
ID: 17892948
> 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

0
 
LVL 86

Expert Comment

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

Author Comment

by:blarouche
ID: 17893022
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
0
 
LVL 92

Expert Comment

by:objects
ID: 17893109
use the getSelectedValue() to get Object from list

eg.

Class clazz = (Class) list.getSelectedValue();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17893141
>>Now system is a String coming from a user selection.


Object x = stringToClass.get(system).newInstance();
0
 
LVL 92

Expert Comment

by:objects
ID: 17893214
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
0
 

Author Comment

by:blarouche
ID: 17893344
I've got a number of unhandled exception

What would be my catch blocks

for example
catch(ClassNotFoundException ect){}
catch(NoSuchMethodException  et){}
0
 
LVL 92

Expert Comment

by:objects
ID: 17894777
> 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
0
 

Author Comment

by:blarouche
ID: 17898242
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 ?
0
 
LVL 92

Expert Comment

by:objects
ID: 17902254
>               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).
0
 

Author Comment

by:blarouche
ID: 17902557
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)
0
 

Author Comment

by:blarouche
ID: 17903218
I am increasing the points because I am stuck with this problem.
0
 
LVL 92

Expert Comment

by:objects
ID: 17903847
thats saying the class does not have a ctor that takes those args, what ctors does SwingTrader have?
0
 

Author Comment

by:blarouche
ID: 17905666
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();
        }
     
    }














0
 
LVL 92

Expert Comment

by:objects
ID: 17905673
>           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});
0
 

Author Comment

by:blarouche
ID: 17905713
objects

You are the best !!


Thank you
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…

634 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question