Solved

Creating a new object from a list choice

Posted on 2006-11-07
23
186 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
  • 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
 

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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
network + 7 73
allStar challenge 1 41
Starting to learn JAVA, 7 48
eclipse package explorer vs project explorer view 2 32
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…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
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…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

758 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now