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.

Similar Messages

  • How to creat odjects with dynamivc class name

    hi i have a problem with class names. i have in my program one father class and a lot of extend classes in the father class. one of this classes is a test class. I want to create an object and the object class must be given dynamic from the keyboard and to be one of the extended classes. how i can do that

    It is possible to create an object of a class whose name is known at runtime (as above, the Class.forName() thing) but it's messy and complete overkill for what you are trying to do.
    These days when I have to distinguish a limited number of words (e.g. car, van,..) I use an enum. You can use MyEnum.valueOf(String name) to find the enum value from an input string, catch IllegalArgumentException to deal with an unmatched input.
    Try something like:
    public enum VehicleType {
        car { public Father create() { return new Car(); }},
        plane { public Father create() { return new Plane();} }.
          .. etc.
      public abstract Father create();
    try {
        Father vehicle = VehicleType.valueOf(vehicleTypeName.toLowerCase()).create();
      } catch(IllegalArgumentException ex) {
         System.out.println("Unknown type " + vehicleTypeName);
    }

  • 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 [code] at the top of your block of code and the tag [/code] at the bottom, like so:
    [code]
      // your code block goes here.
    [/code]good luck

  • 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 to create objects in ABAP Webdynpro?

    Hi,
    I want to create the object for the class: <b>CL_GUI_FRONTEND_SERVICES.</b>
    then i want to call file_save_dialog method.
    how shoud i write the code, plz?

    I have written this code:
    v_guiobj TYPE REF TO cl_gui_frontend_services.
    <u> ?????????????</u>
    v_guiobj->file_save_dialog( ...).
    How to create object in the place of ?????????????.
    Bcoz, when i run this i am getting:
    <b>Access via Null object reference not possible.</b>

  • How to create a weblink to Contact name ?

    Hi experts ,
    How to create a weblink to contact name in report, so that when in i click the Link it show the Contact Detail page.
    We want to do in Data Format in with Custom Text Format .
    please Say how to edit this
    @[html]"{a href=""@H""}"@"{/a}"
    {=<
    }=>
    Thanks in advance
    Edited by: Uthaya on Feb 8, 2011 3:25 AM
    Edited by: Uthaya on Feb 8, 2011 3:37 AM

    Hi,
    I am not sure whether you have something specific in mind by using weblink or do you just want a clickable Contact Name in the report.
    If you just need a report with contact names (and whatever other fields and filters you may want) and when clicked on they take you to the actual record then you can use Action Links
    In your report Add the FullName/Contact Name column and to its immediate right add the Contact ID column (you can make it hidden on the display but it is needed for the action links)
    1. Click on properties for the Contact name column
    2. On the style tab Click on Custom  CSS Style Options (HTML Only) & mark the Use Custrom CSS Class checkbox and type in ActionLink
    3. Go the data format tab and override with Custom Text Format and type/paste in
    @[html]"<span onClick=\"javascript:LinkOccam (this, 'contact');\">"@"</span>"
    The contact names should be clickable and should take you to the actual record when clicked on
    Hoep it helps
    -Gaurav
    Edited by: Gaurav Shah on Feb 8, 2011 12:18 PM

  • Getting class names in jconsole

    Hello,
    Is it possible to get class names which are loaded in the memory using jconsole?
    I am using jdk 1.5. I have configured jmx in my Weblogic 9.2.
    I am able to find the memory usage by the application, but i dont know how to get those class names in jconsole.
    Regards,
    Sampath

    Hi,
    we ckeck all the class names in package.
    first goto se80.select package and give package name and click on display button.it will display all the structures,classes which are assigned to that particular package .in that select class it will expand and displays all the names.
    Cheers,
    vasavi.
    kindly reward if helpful.

  • How to create a model access class ???

    HI,
          Can somebody tell me how to create a Model Access Class. In the Application Set, i can find the Model Access folder, but it has a list of application sets which is already created and the system asks to select a Application set. I need to create a new application set. Please help.
    Regards,
    Shiny

    Hi Shiny,
    I would suggest you not to create a new application set.
    If you are enhancing a standard PCUI application, i would suggest you to create new model access classes and assign them to the same application set which is assigned with the standard model access class for that application.
    Creating a model access class can be done through the transaction SE24(like any other Z-class).
    Go to transaction CRMC_BLUEPRINT_C and you could assign this newly created Model access class to the standard application set. This can be done under Application Element->Application Set->MOdel Access Class.
    If you still feel the need to create a new application set altogether, it can be done from Trx CRMC_BLUEPRINT_C->Layout of PCUI-> Application Element->Application set.
    I hope it helps.
    Cheers,
    Gyan.

  • How to create a client get security token in STS ?

    Dear all,
    How to create a client get security token in STS(security token service supported by Netweaver7.3) ?
    Thanks.

    Hi Sagarika,
    use scc4 for creating a new client
    and login to the new client that u created using sap* and pass as password
    use sccl over there to do a local client copy
    sccl for copying local client
    scc9 for remote client copy
    Merlin

  • How to create object at infoview

    Hi all
    i am using SAP BO 3.1
    How to create object called SL NO this is not available at universe and second object  "code" is coming from universe.
    final output should be like this
    SL NO
    code
    1
    Non-Emergency ED Utilization
    2
    Office Visits
    3
    Inpatient Stays
    thanks in advance!!
    Ranjeet

    Hi Ranjeet
    Insert one column in that report. Write formula like this...
    =LineNumber()-1
    Regards,
    G

  • How to create objects in stack

    I am working on Weblogic 10 and JDK 1.5. In Java the objects are always created in heap. Can anybody tell me how to create objects in stack?

    SKMoharana wrote:
    i need objects to be allocated in stack as my application should respond in real time (time predictable).I heard this is possible in Mustang.If I am understanding you correctly, allocating objects on the stack will not help you, and creating objects on the heap will not hurt you.
    It is provably impossible to create a truly time predictable application (in any language), so what you're really looking to do is create a program that responds acceptably quickly for an acceptable percentage of the time. For this you can create benchmarks like "responds in 250 milliseconds or less 99.5% of the time".
    To this end, you could create a prototype program that creates the objects you wish on the heap, and see if there actually is a problem. Don't fall into the trap of premature optimization.
    Even if you do discover that your object creation IS the problem, heap allocation is not the problem. Take a look at this article. It takes ten machine instructions, less than 1 millisecond, to allocate an object.
    Your performance problems are most likely in the object initialization (look for long loops or deep recursions), the display (if this is a GUI application), or your network connection (if this is a web application).

  • How to create objects to paint itselfs without specifiy the location

    How to create objects to paint itselfs without specifiy the location using Java 2D

    shot in the dark: pass in the Graphics2D context to the method ?

  • How to get class name of a object in run time, from its accessible context.

    Hi,
    I need to get the class name of a java object in run-time, given the AccessibleContext of that object.
    I gone through the AccessibleContext api documentation. but there is not way to get the class name for a java object using its AccessibleContext object.
    Do any one have any idea how to get the class name of an java object, given its accessible object Accessible.
    Thanks
    Timberlake

    816311 wrote:
    Please try to provide a solution for my requirement and avoid evaluating a requirement.
    I am a curious guyit's great to be curious. however, in this situation, the requirement makes no sense in the given context. so, in an effort to be helpful, the people on this forum are asking you the reason behind the requirement. the reason we do this is because we have experience answering questions on this forum and, more often than not, requirements which don't make sense are the result of misunderstandings or confusion on the part of the person making the requirement. if we can figure out why you want to do what you want to do, we may be able to point you in a direction which makes more sense.

  • How to get CLASS name for the generic item?

    Hi,
    I wrote following method to create a service instance.
    public static <IType> IType GetServiceInstance()
           IType type=null;
            try
            InitialContext ic=new InitialContext();
    //ERROR:      type=   ic.lookup(IType.class.getName());
            catch(Exception ex)
            //do handle
            return type;
        }please see the //Error: here its giving error, also i m not getting "class" variable in IDE!!!
    i want use like this;
    IUserService userService=ServiceFactory.GetServiceInstance<IUserService>();so how can i do this?
    Edited by: Manikandan.Java on Oct 31, 2007 3:02 AM

    I don't know if I understand your question, but you cannot find the class name because it is in run time just an object. You can, however, check if it is an instanceof.
    if (genericType instanceof MyType) {
         doMyThing();
    }

  • 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)

Maybe you are looking for