Create objects of distinct classes dinamically

I need to create a method that return and object of the class that indicated in a parameter.
I'm not sure if this topic is related to factory pattern.
I've a class: Parent
I've some classes: Child1, Child2, ... ChildN that extends class Parent.
And I want something like this:
public object CreateChild(String typeofclass)
{ // string typeofclass can contains "child1", "child2" ...
typeofclass c;
(typeofclass) c = new typeofclass();
return c:
I don't want to make something like:
public object CreateClild(Strint typeofclass)
{ if typeofclass.equals ("Clild1");
c = new Clild1();
if typeofclass.equals ("Clild2");
c = new Clild2();
if typeofclass.equals ("ClildN");
c = new ClildN();
return c:
Thanks in advance.
Julio Pe�uela Gil
Barcelona University

public Parent createChild (String typeOfClass) throws Exception
  Class c = Class.forName(typeOfClass);
  return (Parent)c.newInstance();
}have a look at [url http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Class.html]java.lang.Class and the [url http://java.sun.com/j2se/1.4.1/docs/api/java/lang/reflect/package-summary.html]java.lang.reflect package in the API

Similar Messages

  • Dinamically create objects of distinct classes

    I need to create a method that return and object of the class that indicated in a parameter.
    I'm not sure if this topic is related to factory pattern.
    I've a class: Parent
    I've some classes: Child1, Child2, ... ChildN that extends class Parent.
    And I want something like this:
    public object CreateChild(String typeofclass)
    { // string typeofclass can contains "child1", "child2" ...
    typeofclass c;
    (typeofclass) c = new typeofclass();
    return c:
    I don't want to make something like:
    public object CreateClild(Strint typeofclass)
    { if typeofclass.equals ("Clild1");
    c = new Clild1();
    if typeofclass.equals ("Clild2");
    c = new Clild2();
    if typeofclass.equals ("ClildN");
    c = new ClildN();
    return c:
    Thanks in advance.
    Julio Pe�uela Gil
    Barcelona University
    ********************

    Extending this a little bit... i have a similiar thing I want to do.
    I have my class Item, and i have a few classes that extend it. I need to be able to read a list of Item's from a Vector and get the datafield 'type' from the Item class. Based on what this 'type' is, i would make the Item from the Vector the child class of 'type'. I would like to know if this is possible, and if i can do the reverse.
    Thanks,
    CoW

  • How to create object by getting class name as input

    hi
    i need to create object for the existing classes by getting class name as input from the user at run time.
    how can i do it.
    for exapmle ExpnEvaluation is a class, i will get this class name as input and store it in a string
    String classname = "ExpnEvaluation";
    now how can i create object for the class ExpnEvaluation by using the string classname in which the class name is storted
    Thanks in advance

    i think we have to cast it, can u help me how to cast
    the obj to the classname that i get as inputThat's exactly the point why you shouldn't be doing this. You can't have a dynamic cast at compile time already. It doesn't make sense. Which is also the reason why class.forName().newInstance() is a very nice but also often very useless tool, unless the classes loaded all share a mutual interface.

  • Create Object of "ObjectName" Class by giving only Domain Name.

    Hie,
    I want to create Object of "ObjectName" class without specifying its key value properties, but i want to only specify the domain name.
    For eg:
    ObjectName on=new ObjectName("jboss.ws4ee:*"); here jboss.ws4ee is the domain name and after colon(:) will come the key value properties.. i dont want to specify that because i want the list of all mbeans coming under this domain i.e. jboss.ws4ee
    So anyone can plzzz help me..
    Regards.

    Hi,
    What were you trying to do with that name?
    ObjectName on=new ObjectName("jboss.ws4ee:*");
    You cannot create an MBean with such an ObjectName. You can only
    use it as first argument to queryNames() and queryMBeans();
    If you want to get the attributes of all jboss MBeans then you will need to
    do something like that:
    final ObjectName pattern=new ObjectName("jboss.ws4ee:*");
    for (ObjectName o : server.queryNames(pattern,null)) {
        System.out.println("MBean:  " + o);
        for (MBeanAttributeInfo info : server.getMBeanInfo(o).getAttributes()) {
             final String attrname = info.getName();
             System.out.println("\t"+attrname+"="+server.getAttribute(o,attrname));
    }(disclaimer: this code was eyed-compiled)
    hope this helps,
    -- daniel
    JMX, SNMP, Java, etc...
    http://blogs.sun.com/jmxetc

  • How do i create objects of ordinary Classes from a javabean

    I want to create a class Person below that I want to create an object from in my javabeans.
    Look below Person class definition for continuation.
    package data;
    public class Person
    private String name;
    public Person()
    name = "No name yet.";
    public Person(String initialName)
    name = initialName;
    public void setName(String newName)
    name = newName;
    public String getName()
    return name;
    public void writeOutput()
    System.out.println("Name: " + name);
    public boolean sameName(Person otherPerson)
    return (this.name.equalsIgnoreCase(otherPerson.name));
    I run this bean class in the WEB-INF/classes/data folder creating a Person object in the deal() method below
    When I compile the class it seems to fail. It does not recognise the Person class. Can you help me with a description of what to do to call
    ordinary class objects from javabean class definitions.
    What directories should the simple classes be put and what should I include in the javabean to be able to access them?
    package data;
    import java.sql.*;
    import data.*;
    public class Bean
    { private Connection databaseConnection ;
    // private Person p;
    public Bean()
    super();
    public boolean connect() throws ClassNotFoundException, SQLException
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String sourceURL = "jdbc:odbc:robjsp";
    databaseConnection = DriverManager.getConnection(sourceURL);
    return true;
    public ResultSet execquery(String restrict) throws SQLException
    Statement statement = databaseConnection.createStatement();
    String full = "SELECT customerid,CITY,Address from customers " + restrict;
    ResultSet authorNames = statement.executeQuery(full);
    return (authorNames ==null ) ? null : authorNames;
    public String deal() throws SQLException
    {  Person p = new Person();
    p.setName("Roberto");
    return p.getName();
    }

    There is no "Copy File" function in Lightroom.
    Lightroom was designed to eliminate the need to make duplicate copies of files. The organizational tools in Lightroom allow you to have one file categorized in many ways, you can assign multiple keywords to the photos (for example: Winery, Finger Lakes, Fall Foliage, Jessica). Similarly, you can have a file categorized in multiple Lightroom collections at the same time, all without making a copy of the photo. The benefit of this is that you don't need to make multiple copies of each photo, one copy suffices, and thus disk space is saved; and furthermore if you should edit a photo or add metadata, you only need to do this once, and the photo's appearance, or the photo's metadata is changed, and visible to you no matter how you choose to access the photo (pick any keyword or any collection and you will see the change)

  • Create  object for a class in jar file

    Hi
    I am using Oracle JDeveloper 10g. I have created a main application using Swing/JClient technologies. I am facing a problem for the past one week. I let u all people know my problem and I kindly request you to send a solution if known possibly confirmed.
    Problem: I have created a main application using swing that class extends JFrame. This main application consists of two parts. One left side panel and one right side panel. Left side panel contains JTree component. Each item in that tree refers to a class file located in a separate jar file.i.e that acts as a separate application. If we are executing separately that jar file class, I am able to see that small application running. If I am selecting an item in JTree during runtime, I should place that small application from the respective jar file in the right side panel of the main application. I can locate the jar file and even I can create object to that particular class file. But I cannot execute the application even separately and also not able to place in the right side panel of the main application.
    Note: The small application from the jar file contains one class file containing main method. That class file extends JPanel and implements JUPanel. i.e., with data binding. I am trying to create an object for this class file with data binding from my main application. Navigation bar is used in the main class file.
    If possible can any provide me solution at the earliest. Waiting eagerly for the positive reply.
    Regards,
    s.senthilkumar

    Can you sure that there is only a A class in the classpath of Tomcat, I advise you to add
    some statements into the A class so that you can be sure which classloader is used
    to load the A class.

  • POWL- Create object for feeder class not found

    Hi,
    I have developed a Webdynpro application and tried to integrate to POWL, but the application dumps saying cretae object of feeder class is not found.
    I am new to POWL, can anybody help me in this regard.
    Thanks,
    Shailaja Ainala.

    - in se80 you need this kind of code
        AUTHORITY-CHECK OBJECT 'Z:CPRO_RAP'
        ID 'ZZ_MARKDIV_test' FIELD record-string+0(3)
        ID 'ACTVT'      FIELD '02'.                                         "change access
        IF sy-subrc <> 0.
          AUTHORITY-CHECK OBJECT 'Z:CPRO_RAP'
          ID 'ZZ_MARKDIV_test' FIELD record-string+0(3)
          ID 'ACTVT'      FIELD '03'.                                      "read only access
          IF sy-subrc = 0.
            is_allowed = abap_true.
          ENDIF.
        ELSE.
          is_allowed = abap_true.
        ENDIF.
    security team should setup the POWL
    http://help.sap.com/saphelp_erp60_sp/helpdata/en/44/36ca0563df660ee10000000a1553f6/content.htm
    http://help.sap.com/saphelp_erp60_sp/helpdata/en/42/d6652b755c1630e10000000a1553f7/content.htm
    so if you see the code above there is a ID and filed associated with each object.

  • Trying to create object of a class within servlet - help!!

    I have created and compiled the following classes within
    C:\bea\wlserver6.1\config\mydomain\applications\DefaultWebApp\WEB-INF\classes
    1)LoginServlet
    2)LoginManager
    3)I have LoginServlet trying to create an object of type LoginManager, very simple,
    but I get the following errors:
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    4)I have the .java and .class files located within the same directory, so I don't
    see what's wrong here??? HELP!
    LoginManager looks like:
    public class LoginManager {
    public boolean authenticateUser(String username, String password){
              boolean status = false;
    //simple code for string matching
              return status;
    LoginServlet looks like:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class LoginServlet extends HttpServlet {
         // Constructors
         // Variables
         public static final String CONTENT_TYPE = "text/html";
         public boolean LOGIN_STATUS;
         // Methods
         public void service (HttpServletRequest req, HttpServletResponse res)
              throws IOException {
              String username = "";
              String password = "";
              LoginManager lm = new LoginManager();
              username = req.getParameter("username");
              password = req.getParameter("password");
              LOGIN_STATUS = lm.authenticateUser(username, password);
              res.setContentType(CONTENT_TYPE);
              PrintWriter out = res.getWriter();
              out.println("<html><head><title>Hello World</title></head>" +
                             "<body>Hello! Your login status is " + LOGIN_STATUS +
                             "</body>" +
                             "</html>");
         public void init (ServletConfig config) throws ServletException {
              super.init(config);

    Do you have . in the CLASSPATH when compiling your servlet?
    ron <[email protected]> wrote:
    I have created and compiled the following classes within
    C:\bea\wlserver6.1\config\mydomain\applications\DefaultWebApp\WEB-INF\classes
    1)LoginServlet
    2)LoginManager
    3)I have LoginServlet trying to create an object of type LoginManager, very simple,
    but I get the following errors:
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    4)I have the .java and .class files located within the same directory, so I don't
    see what's wrong here??? HELP!
    LoginManager looks like:
    public class LoginManager {
    public boolean authenticateUser(String username, String password){
              boolean status = false;
    //simple code for string matching
              return status;
    LoginServlet looks like:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class LoginServlet extends HttpServlet {
         // Constructors
         // Variables
         public static final String CONTENT_TYPE = "text/html";
         public boolean LOGIN_STATUS;
         // Methods
         public void service (HttpServletRequest req, HttpServletResponse res)
              throws IOException {
              String username = "";
              String password = "";
              LoginManager lm = new LoginManager();
              username = req.getParameter("username");
              password = req.getParameter("password");
              LOGIN_STATUS = lm.authenticateUser(username, password);
              res.setContentType(CONTENT_TYPE);
              PrintWriter out = res.getWriter();
              out.println("<html><head><title>Hello World</title></head>" +
                             "<body>Hello! Your login status is " + LOGIN_STATUS +
                             "</body>" +
                             "</html>");
         public void init (ServletConfig config) throws ServletException {
              super.init(config);
    Dimitri

  • Is it posible to create objects with different names dinamically?

    Hi,
    I'm creating an app that manages different wireless nodes in a network and I was thinking that I could create a class called Node which would have a constructor that every time I created an object Node, I would pass the address and some other data about the Node and the constructor will save all that data and also create a unique ID for every Node object.
    Now the problem is that I need to be able to discover all the nodes in my network every time the user clicks a Ping button. So every time the users clicks Ping I need to do a ping and create as many Node objects as nodes I have in my network. The thing is I don't know how to make it create the node objects with different names so after I've created all the nodes objects I can refer to one of them.
    Something like this.
    int Id=0;
    id++;
    Node node+Id = new Node();
    I think its not possible to do something like that. If it isn't how can I do to refer to one of the objects I've created?
    Thanks.

    Twistx77 wrote:
    Thanks to both of you. I'll check out the Link and if I can't find the solution there I'll make the array , I don't know how I didn't think about doing that. There are two collections you should study specifically:
    First you have the ArrayList which in essense is a growable array. This means you don't have to decide in advance how big it can be.
    Second there's the HashMap. It's sometimes called an associate array. Such an array doesn't have fixed position indexes like an ordinary array. Instead each index (called key) is associated with a value but the keys don't have any particular order. Still, given a certain key, finding the corresponding value in a HashMap is almost as fast as an array access.

  • How i create object of this class

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.print.PrinterException;
    import java.text.MessageFormat;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class vendor extends JDialog // probably best to use a JDialog, not a JFrame here
    // make some instance variables
    private String rows[][] =
    {"A", "a"},
    {"B", "b"},
    {"E", "e"}
    private String headers[] =
    "Upper", "Lower"
    private JTable table = new JTable(rows, headers);
    // here's the constructor.
    public MainClass(JFrame frame, String title, boolean modal)
    super(frame, title, modal);
    //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane, BorderLayout.CENTER);
    JButton button = new JButton("Print");
    ActionListener printAction = new ActionListener()
    public void actionPerformed(ActionEvent e)
    printActionPerformed(e);
    button.addActionListener(printAction);
    add(button, BorderLayout.SOUTH);
    setPreferredSize(new Dimension(300, 150));
    //frame.setSize(300, 150);
    //frame.setVisible(true);
    private void printActionPerformed(ActionEvent e)
    try
    MessageFormat headerFormat = new MessageFormat("Page {0}");
    MessageFormat footerFormat = new MessageFormat("- {0} -");
    table.print(JTable.PrintMode.FIT_WIDTH, headerFormat,
    footerFormat);
    catch (PrinterException pe)
    System.err.println("Error printing: " + pe.getMessage());
         public static void main(String x[])
    {new vendor();}
    }

    You have to call it from a JFrame or other root container:
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class UseDialog extends JPanel
        private JFrame frame = null;
        private MainClass myDialog = null;
        public UseDialog(JFrame frame)
            setPreferredSize(new Dimension(300, 200));
            this.frame = frame;
            JButton showDialogBtn = new JButton("Show Dialog");
            add(showDialogBtn);
            showDialogBtn.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    showDialogBtnAction(e);
        private void showDialogBtnAction(ActionEvent e)
            //*********** here is where it is called **************
            myDialog = new MainClass(frame, "My Dialog", true);
            myDialog.pack();
            myDialog.setVisible(true);
        private static void createAndShowGUI()
            JFrame frame = new JFrame("UseDialog Application");
            frame.getContentPane().add(new UseDialog(frame));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }Also, when posting your code, please use code tags so that your code will be well-formatted and readable. To do this, place the tag &#91;code&#93; at the top of your block of code and the tag &#91;/code&#93; at the bottom, like so:
    &#91;code&#93;
      // your code block goes here.
    &#91;/code&#93;good luck

  • TestStand create different object for singleton class

    Hi all,
    we have a singleton class which has some functions used to do testing a harware.
    Our main Exe will create an object for that singleton class(which opens Com1 port and communicate with hardware). so the Exe will do basic communication test with hardware it is working well. We are using Teststand operator interface to do various testing by using sequence files. Main exe will use teststand usercontrols to execute tests when the user clicks Testbutton. after that, teststand try to create an object for that singleton but it returns new object not the existing one which is created by EXE. So it throwing me exeception "Com1 port access denied." (since we created object for signleton class @ very first in EXE)
    My question is Since that teststand runs in a separate Appdoamin will the singltonclass create separate object for different appdomain? if so is there any solution to reslove this?
    Hope i clearly explained my probs.
    Thanks in advance
    Srini 

    Hi Srini,
    How are you calling the executable?  From a Call Executable step?  Or are you using another means of calling it?   Also, why is TestStand trying to recreate the object?  As long as you have the correct handle to the object I don't think it matters what app domain you are in.
    Regards,
    jigg
    CTA, CLA
    teststandhelp.com
    ~Will work for kudos and/or BBQ~

  • How can the servlet engine create objects of interfaces?help

    hello,
    I have this basic fundamental query...when using servlets i noticed that so many methods in the HttpServlet class take as arguments objects of the type "Interface"..where as basic principle in java is u cant instantiate interfaces...interfaces r mere templates which u implement by ur own custom classes.
    For example the doGet method recieves from the servlet engine(servlet container) two arguments which r HttpServletResponse object and HttpServletRequest object..and u use these further to make use of the methods of the inmterfaces..which again is a mystery to me...why?
    here is why:-
    since HttpServletResponse and HttpServletRequest r interfaces..they cant be instantiated...and now that the sevlet engine provides objects of these interfaces...how come u r able to to use the methods of these interfaces...for r they not empty methods?..
    example how r u able to make the sendRedirect() method of HttpServletResponse interface work...is this method not an empty method?
    there r several interfaces...whose objects r being used and passed in this similar fashion....(for example there r many methods that return an enumeration...which is used as if it were an ordinary class that can be instantiated..and whose methods r non empty emthods)
    please help me resolve this mystery
    sheeba

    Don't call me "u". The word is "you". Likewise "are" and not "r".
    The servlet engine creates objects of concrete classes that implement those interfaces. If you want to find the names of those classes in your particular server, you could use for examplereq.getClass().getName()

  • Exporting Parameters while creating objects

    Hi,
    While creating objects to a class,we can see few parameters with the object created.Any idea about where the parameters are coming from and what are the values to be passed for it should be helpful.
    For ex:
    I am creating a object for CL_DD_DOCUMENT.
       CREATE OBJECT e_dyndoc_id
         EXPORTING
           STYLE  =
           BACKGROUND_COLOR =
           BDS_STYLESHEET =
           NO_MARGINS =
    I am able to see BDS_STYLESHEET in attributes.
    But where I can see the other parameters?How to set the values for those parameters?

    possibel styles:
    'ALV_GRID'.
    'ALV_TO_HTML'.
    'TREE'.
    'STAND_ALONE'.
    taken from the local class implemented within CL_DD_DOCUMENT
    how to reach this code.
    go to the source view of the constructor method of cl_dd_document.
    double click on method "initialize_document"
    double click on method "get_gui_properties"
    in the following statement there.
    call method resources->get_gui_properties
    now you will see these styles.
    Regards
    Raja

  • Why can't I create new object from a class that is in my big class?

    I mean:
    class A
    B x = new B;
    class B
    and how can I solve it if I still want to create an object from B class.
    Thank you very much :)

    public class ItWorksNow  {
      public ItWorksNow() {
      public static void main ( String[] argv )  throws Exception {
        ItWorksNow.DaInnaClass id = new ItWorksNow().new DaInnaClass();
      public class DaInnaClass {
    }

  • Adding ItemListeners to an object created in an inner class?

    Hi All,
    I was wondering how dow you add ItemListeners to an object, thats created in an inner class of an outer class that implements the item listener interface. Or is it possible? I got around the problem by putting the createBox method in the outer class and calling it from the inner class, but it would be nice to know if you can keep it contained.
    i.e (Assume everythings declared, libs are imported, interface is implemented in outer class etc.)
    public class OuterClass implements ItemListener
        // Stuff
        class InnerClass
            // Yet more stuff
            void createBox (JPanel aPanel)
                 JCheckBox aBox = new JCheckBox;
                 aPanel.add(aBox)
                 // What should this line be ->
                 aBox.addItemListener(whatGoesHere?);
        // More Stuff
    }

    aBox.addItemListener(OuterClass.this);

Maybe you are looking for