Create an instance of a class from class name

Hi,
I have the class name as a String variable. I need to create an instance from this class. How to do it in Java?
   Thanks and regards, Marina

Hello
see
[http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String)]
and
[http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#newInstance()]
for Classes with paramterless constructor
or
[http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/Constructor.html#newInstance(java.lang.Object[])]
for Constructor with parameters
regards franz

Similar Messages

  • How to create an instance of a dynamically loaded class?

    Hi all,
    I am using ASM bytecode engineering framework to generate classes dynamically. I need to instantiate the classes dynamically as well. Request all to please enlighten me on the following points :
    (1) Presently I load the class using a custom class loader and then use Class.newInstance() method to obtain an instance. However, I read that reflection is slow. So is their a faster way to instantiate in this case?
    (2) The name of the classes are also generated automatically. And I don't know which class will actually be instantiated at runtime. So I have to store the refernce returned by Class.newInstance() in an Object type variable. And when I wish to invoke a method / access a data member on that instance, every time I need to cast the object to the appropriate class using Class.cast(). Can anyone please suggest a more efficient way to hold the reference?
    Thanks and Regards,
    Vinit_J

    Have those classes implement a particular interface, and hold the instances in references to that interface. If you're thinking "that's a bit restricting" then maybe you should re-think whether loading a class whose responsibilities are completely unknown at compile-time is as useful as you first thought it was

  • How to create and instance of Java Object from an XML Document.

    Hi,
    How can we use a XML Document to create an instance of Java Object and do vice versa ie from the Java Object creating the XML Document.
    XML Document is available in the form of a String Object.
    Are there helper class available to achieve this.
    I need to do this in a Servlet.
    Regards
    Pramod.

    JAXB is part of JavaSE while Xmlbeans claims full schema support and full infoset fidelity.
    If the standard APIs do all that you need well then use them.

  • How to load a class from its name.

    Hi,
    In my program, I want users can write their own classes, these classes need to implement an interface and name of class will be stored in database. I use Class.forName() to load these classes but I cannot type-cast to interface. Please help me.
    Here is the code in my program:
    public interface A {
    public void doSomething();
    public class test {
    public static void main(String[] args) {
    A clazz = (A)Class.forName("MyClass"); // error here
    A.doSomething();
    }

    Hai,
    Refine your test class as follows:
    public class test
    public static void main(String arg[])
    try
    Class clazz = Class.forName("MyClass");
    Object obj = clazz.newInstance();
    ((MyClass)obj).doSomething();
    catch(Exception ex)
    System.out.println(ex);
    Regards
    Raja.

  • ADF viewScope is creating new instance without navigating away from view

    Hello,
    I'm using JDeveloper version 11.1.1.6.0.
    In a Portal application, I'm using view scoped Managed Beans. When I navigate to a page, as expected one instance of the Bean is created. I have dependent selectOneChoice objects inside this page, therefore a partial page refresh is generated when the user chooses a value, a value change listener is called, I read bean variables and do my thing. But here's the catch, a new instance of the Managed Bean is created before the value change listener is called. I have no idea why. According to documentation the viewScope bean should persist until the viewId changes. The end result is I'm screwed trying to read variables that should persist from page load inside this value change listener.
    But wait, that's not all. The issue here is the very first partial page refresh (or whatever it should be called). Only the first partial page refresh will cause the creation of a new managed bean instance. Any subsequent ones will not.
    So it goes like this:
    Page load -> @PostConstruct runs once -> Partial page refresh -> @PostConstruct runs again -> Partial page refresh -> @PostConstruct doesn't run -> Partial page refresh -> @PostConstruct doesn't run...
    I'm really at a loss of options here, the @PostConstruct running twice inside the very same view in a viewScope Bean is news to me. But then again, I'm new to ADF so what do I know. I noticed this happens with every viewScope bean in my application, not just this particular one. It just so happens that only in this case this became a problem.
    I'm in an all out war against this thing for more than a day now. The internet is my last resort before I make some dumb workaround that will consume me in my sleep. Any help is greatly appreciated.
    Edited by: 934172 on Sep 6, 2012 12:35 PM
    Edited by: 934172 on Sep 6, 2012 12:36 PM

    I'm determined to fix this thing no matter what the hell it takes.
    I found out exactly what is happening, even though I'm not sure why it happens. But the important question here is how to fix it.
    Here is the first request, the one that happens when I navigate to the page:
    http://localhost:7101/teste-Portal-context-root/faces/pages_test?_adf.ctrl-state=18hjxv8lyw_4Here are all the subsequent ones, the ones that happen when I select a choice:
    http://localhost:7101/teste-Portal-context-root/faces/oracle/webcenter/portalapp/pages/test.jspx?_adf.ctrl-state=18hjxv8lyw_4It's no wonder the server is confused and creates a new bean instance. Now what the hell? Why are they different? But more importantly, can I fix the first one? Can I force the bean created by the first one to answer for the second one?
    I still don't know. But hopefully I'll find out.

  • How to create new instance of the process from external web apps?

    Hi Everyone,
    How to create a new instance of the process which deploy to the weblogic server from the external web app?
    Thank you.

    Assuming the process includes a message start event, the simplest way is to use Web Service call. Once you've deployed the process you can use Enterprise Manager to get the URL of the WSDL. There's and icon at the top of the composite summary page for getting the WSDL, or you can get it from the test page. Use that WSDL URL to construct the client to use from the web app. If it's an ADF client you can generate either an ADF Data Control or a client proxy.

  • Calling Class from Class

    Hi,
    I am sure this is a very basic question but I don't have anyone to ask, have tried a few formats but it does'nt like it. I have two compiled classes and wish to call one from the other, can anyone give me the format to do this?
    Thanks,
    Neil Mc

    class WotifReff {
        public static void main(String[] args) {
            WotifReft wotifreft = new WotifReft();
            wotifreft.call();
            WotifRef2 wotifref2 = new WotifRef2();
            wotifref2.call();
    }The only method that exists in your class is called "main". However you are attempting to call a method called "call". It does not exist. You can only call methods that do exist. So try adding that method to your class.
    class WotifReff {
        public static void main(String[] args) {
            WotifReft wotifreft = new WotifReft();
            wotifreft.call();
            WotifRef2 wotifref2 = new WotifRef2();
            wotifref2.call();
        public void call() {
            System.out.println("Now the code will compile");
    }OOPS! Misread your class names.
    class WotifReff {
        public static void main(String[] args) {
            WotifReft wotifreft = new WotifReft();
            wotifreft.call();
    class WotifReft {
        public void call() {
            System.out.println("Now the code will compile");
    }That should work.

  • Creating an instance of a class at runtime?

    Does anyone know how to create an instance of a class at RunTime? For example, I want to load classes from a JAR file at RunTime, and then create instances of certain classes of each JAR. I ask this because I do not see how to create an instance of one of those classes the traditional way, SomeClass var = new SomeClass(). I am pretty sure that someone out there has done this and succeeded in doing it. All of the post on this stuff only talk about loading the class from a JAR file, but I have already loaded them using URLClassLoader�s findClass() method. I have also created an instance of the class that findClass() returns using newInstance(), but newInstance() returns an object of type Object. How can I convert this object to an object of type SomeClass? You cannot cast it because the compiler will complain due to the import statement issue. So if you cannot include the import statement because that classpath does not exist, then how the heck would you cast the newInstance() object into a SomeClass object?

    You can cast the returned object to the type you need...that is what I do in my applet. The trick is that you must get the instance of the applets class loader (or you get a classCastException). Pay attention to this line below - that's the real key here.
    "// Get a reference to the applets own classloader"
    protected CBaseQuestionnaireFile m_BaseObject = null;// declared up front
    m_BaseObject = loadAndRunClass("com.cpm.dataentry.questionnaire.CQuestionnaireFile");// fully qualified base object
    Here is the load and run method:
       CBaseQuestionnaireFile loadAndRunClass(String classname)
          com.cpm.common.base.CBaseQuestionnaireFile questBase = null;
          Class cClass = null;
          try
             // first we open the jar file with the classes we need
             String[] aJarList = new String[10];
             // Questionnaire format file
             File fURL1 = new File(GetMainFrame().m_strQuestionnaireFileName);
             URL url1   = new URL(fURL1.toURL(),"");
             URL urlNew = new URL("jar:" + url1.toExternalForm() + "!/" );
             // Server base class directory
             String strServerDirectory = "http://" + GetMainFrame().m_strHost + "/APPLETS/";
             File fURL2 = new File(strServerDirectory);
             URL url2 = new URL(fURL2.toURL(),"");
             URL urlNew2 = new URL("jar:" + url2.toExternalForm() + "!/" );
             // Local base class directory
             String strLocalDirectory = CSystem.GetBasePath() + "/Research/bin/";
             File fURL3 = new File(strLocalDirectory);
             URL url3 = new URL(fURL3.toURL(),"");
             URL urlNew3 = new URL("jar:" + url3.toExternalForm() + "!/" );
             File fURLBase = new File(CSystem.GetBasePath() + "/Research/bin/base.jar");
             URL urlBase = new URL(fURLBase.toURL(),"");
             URL urlNewBase = new URL("jar:" + urlBase.toExternalForm() + "!/" );
             File fURLControl = new File(CSystem.GetBasePath() + "/Research/bin/controls.jar");
             URL urlControl = new URL(fURLControl.toURL(),"");
             URL urlNewControl = new URL("jar:" + urlControl.toExternalForm() + "!/" );
             File fURLUtil = new File(CSystem.GetBasePath() + "/Research/bin/utlities.jar");
             URL urlUtil= new URL(fURLUtil.toURL(),"");
             URL urlNewUtil = new URL("jar:" + urlUtil.toExternalForm() + "!/" );
             // Determine where to look
             URL[] urlList = null;
             if(GetMainFrame().m_isStandalone == false) {
                // From a browser
                CSystem.PrintDebugMessage("Running as an applet");
                if(GetMainFrame().m_bOnLineMode == true) {
                   // On line
                   CSystem.PrintDebugMessage("*** On Line Mode ***");
                   urlList = new URL[2];
                   urlList[0] = urlNew;
                   urlList[1] = urlNew2;
                else {
                   // Off line
                   CSystem.PrintDebugMessage("*** Off Line Mode ***");
                   urlList = new URL[4];
                   urlList[0] = urlNew;
                   urlList[1] = urlNewBase;
                   urlList[2] = urlNewControl;
                   urlList[3] = urlNewUtil;
              else {
                 CSystem.PrintDebugMessage("*** Stand Alone Mode ***");
                 urlList = new URL[1];
                 urlList[0] = urlNew;
    CSystem.PrintDebugMessage("Question file/path: " + GetMainFrame().m_strQuestionnaireFileName);
            // Set the wait cursor
            GetMainFrame().SetWaitCursor();
            // Get a reference to the applets own classloader
            Class myClass = getClass();
            ClassLoader appletClassLoader = myClass.getClassLoader();
            // Call our multi-jar class loader
            JarClassLoader jarLoader = new JarClassLoader(urlList,appletClassLoader);
    CSystem.PrintDebugMessage("CPM Test - passed Jar Loader" + jarLoader.toString());
             // Load the classname from the jarfile
             try
                  cClass = jarLoader.loadClass(classname);
             catch(ClassNotFoundException cnfe)
                Object[] optionsConfirm = { "Ok" };
                JOptionPane.showOptionDialog(GetMainFrame(),"Questionnaire file is either damaged or has been tampered with.", "Questionnaire File Error",
                JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, optionsConfirm, optionsConfirm[0]);
                GetMainFrame().m_strQuestionnaireFileName = "";
                // Clear the wait cursor
                GetMainFrame().ClearWaitCursor();
                return null;
             Class cSuperclass = cClass.getSuperclass();
    CSystem.PrintDebugMessage("Test Superclass type is: " + cSuperclass.toString());
             Object o = cClass.newInstance();
    CSystem.PrintDebugMessage("Test plain class type is: " + o.toString());
             // Never remove this line of code
             // without it, a crafty user could use our load routine
             // to load/and run some nasty code
             // This test makes SURE that *ONLY* questionnaires get opened
             // and their methods get called
             if(o instanceof com.cpm.common.base.CBaseQuestionnaireFile)
                // Create the object
    CSystem.PrintDebugMessage("Test Is instance of CBaseQuestionnaireFile");
    CSystem.PrintDebugMessage("CPM Test - Casting to Base Class");
                questBase = (com.cpm.common.base.CBaseQuestionnaireFile)o;
    CSystem.PrintDebugMessage("CPM Test - Getting languages from questionnaire");
                GetMainFrame().GetLanguagesFromQuestionnaire(questBase);
    CSystem.PrintDebugMessage("CPM Test - Setting locale from Questionnaire selection");
                questBase.SetQuestionnaireLocale(GetMainFrame().m_locale);
    CSystem.PrintDebugMessage("CPM Test - Initializing Questionnaire");
                questBase.Initialize();
                questBase.InitializeCards();
              else
                Object[] optionsConfirm = { "Ok" };
                JOptionPane.showOptionDialog(GetMainFrame(),"Questionnaire file is either damaged or has been tampered with.", "Questionnaire File Error",
                JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, optionsConfirm, optionsConfirm[0]);
                GetMainFrame().m_strQuestionnaireFileName = "";
                // Clear the wait cursor
                GetMainFrame().ClearWaitCursor();
                return null;
          catch (Exception e)
              exDialog.showForThrowable(e.toString(),e);
         // Clear the wait cursor
         GetMainFrame().ClearWaitCursor();
         // Set MouseListener Pointer
    //     questBase.SetMouseListenerPointer(GetMainFrame().m_mouseListener);
         return questBase;
       }

  • Problem in loading a class from server

    hello,
    Please help me ,i m using this code to load a class from server and this code load this successfully but i don't how to make object of class that is just loaded.
    i want to load the class and use its method in my program please help me i m in very critical position.
    pelase help me give me hint
    import java.sql.*;
    import java.net.*;
    import java.io.*;
    public class MyLoader
    public static void main (String argv[]) throws Exception
    URLClassLoader loader = new URLClassLoader(new URL[] { new URL("url") });
    // Load class from class loader. argv[0] is the name of the class to be loaded
    String str = "FinalMyConnection";
         Class c = loader.loadClass (str);
    System.out.println(c.getClass().getName());
    // Create an instance of the class just loaded
    Object o = c.newInstance();
         System.out.println(o.getClass());
         FinalMyConnection mycon = new FinalMyConnection();
         String query1 = " select * from game_master order by game_id;";
         mycon.connect();
              ResultSet rs1=mycon.executequery(query1);
              while (rs1.next())
              String s1=rs1.getString(1);
                   String s2=rs1.getString(2);
                   System.out.println("game_id"+s1);
                   System.out.println("game_name"+s2);
    }

    also load all required parser and sax classes into oracle,i.e.,
    you can load the '.jar' file containg all the parser and sax classes and then load you ContentHandler class.

  • Referencing main class from created instances

    The quick setup:
    My Main class creates a JFrame and adds a few custom JPanels. One of the JPanels has a mouse listener and responses to the mouse clicks, and it works great.
    I'd like to know if there's a way to have that JPanel invoke public, non-static methods from the Main class (the class which created it) without passing a reference for the instance of the Main class to the JPanel when it's (the JPanel) is created. Or is that the way you're supposed to do it?
    A (sort of) similar question: can a component invoke methods of it's parent container? If so, how?
    Thanks so much,
    Matt

    Hi Rhesus21,
    A (sort of) similar question: can a component invoke methods of it's parent container? If so, how?Yes, simply this way :
    public class MainFrame extends JFrame {
        private MyPanel panel;
        panel = new MyPanel(this);
    public class MyPanel extends JPanel {
        private MainFrame frame;
        public MyPanel(MainFrame frame) {
            this.frame = frame;
    }

  • How to call a method from a class without creating an instance fromthisclas

    I want to create a class with methods but I want to call methods from this class without creating an instance from this class. Is this possible?
    Is there in Java something like class methods and object methods????

    keyword 'static' my friend.
    public class foo {
    public static void bar {
    System.out.println ("hello");
    foo.bar()

  • Creating an instance of a class from within another class

    I am trying to create an instance of MCQ in the T class but I am getting this error:
    File: E:\JAVA PROGRAMS\assignment 1\T.java [line: 15]
    Error: cannot find symbol
    symbol : class MCQ
    location: class T
    here are the two classes:
    // class T
    import java.awt.*;
    import java.util.*;
    import java.lang.*;
    public class T{
    public T(String aT)
    pest = aT;
    public static T t_one()
    T aT = new T("Calculator");
    aT.addQ(new MCQ( " 2 + 2", "equals 4", "equals 5", "equals 0", " equals -2",
    "is a prime number", 1));
    return aT;
    private String pest;
    //class Q
    import java.awt.*;
    import java.util.*;
    import java.lang.*;
    public abstract class Q{
    Vector q = new Vector();
    public String aT;
    abstract void addQ(Q aQ);
    public class MCQ extends Q{
    String a,b,c,d,e,f,g;
    int answer;
    public MCQ (String a, String b, String c, String d, String e, int answer)
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.answer = answer;
    void addQ(Q aQ)
    q.addElement(new T(aT));
    I tried to make reference to MCQ by doing this in class T:
    MCC qT = new MCQ() ;
    but that presents a whole other set of problems.
    please help I think I have tried everything!

    Use code tags (http://forum.java.sun.com/help.jspa?sec=formatting)
    Don't import java.lang.* . You get those automatically.
    Your MCQ class is really Q.MCQ (the way you posted, anyway).
    If Q weren't abstract, you could do:
    new Q().new MCQ(...)But, you can't create a Q without defining 'add'. You could do it anonymously, but that makes no sense. Put Q and MCQ in separate files and try again.

  • Error creating instance of class from same package

    When I try to create an instance of a class that is in the same package, my IDE indicates that the constructor can not be found. Can anyone tell me what is wrong? Thanks. Below are the codes for both classes:
    package com.practice;
    import java.applet.*;
    import java.awt.*;
    import javax.swing.*;
    public class WebProject extends Applet{
         public void init(){
                    // The following line is where the IDE indicates there is an error
              UserInterface gui = new UserInterface();
         } // end init()
         public void start(){
         } // end start()
         public void stop(){
         } // end stop()
         public void destroy(){
         } // end destory()
    } // end class
    package com.practice;
    import java.applet.*;
    import java.awt.*;
    import javax.swing.*;
    public class UserInterface extends Applet{
         JPanel menuPanel = new JPanel();
         JPanel contentPanel = new JPanel();
         JPanel savePanel = new JPanel();
         ImageIcon saveIcon = new ImageIcon("workspace/images/toolbarButtongraphics/general/Save24");
         JButton saveButton = new JButton("Save", saveIcon);
         public UserInterface(){
              savePanel.add(saveButton);
              setLayout(new BorderLayout());
              add(menuPanel, BorderLayout.NORTH);
              add(contentPanel, BorderLayout.CENTER);
              add(savePanel, BorderLayout.SOUTH);
    } // end UserInterface class

    Thanks for the explanation and example. At first, I didn't understand what you were getting at, but after reading "Using Top-Level Containers" and "How to Use Root Panes" java tutorials it made much more sense. Unfortunately, the books I've read up to this point, did not cover those topics at all. The books simply stated that the first step in creating a Swing gui was to extend the JFrame, or JApplet, or etc.
    Unfortunately, my original problem persists. I continue to get compile-time errors such as:
    TestUserInterface.java:5: cannot find symbol
    symbol: class UserInterface
    location: class projects.web.TestUserInterface
                          UserInterface ui = new UserInterface(); Anyone know why?
    Both the classes are in the same named packaged. Below is my code:
    package projects.web;
    import java.awt.*;
    import javax.swing.*;
    public class UserInterface extends JFrame{
         JPanel menuPanel = new JPanel();
         JPanel contentPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         JButton save = new JButton("Save");
         JButton addFiles = new JButton("Add");
         public UserInterface(){
         super("File Upload");
         setSize(500, 500);
         menuPanel.add(addFiles);
         selectionPanel.add(save);
         setLayout(new BorderLayout());
         add(menuPanel, BorderLayout.NORTH);
         add(contentPanel, BorderLayout.CENTER);
         add(selectionPanel, BorderLayout.SOUTH);
         } // end constructor
    } // end UserInterface class
    package projects.web;
    public class TestUserInterface{
         public static void main(String[] args){
              UserInterface ui = new UserInterface();
    } // end TestUserInterface class

  • Coldfusion create instance of class from data element when cosuming a webservice

    I am calling the following wsdl via cfobject https://services-staging.labcorpsolutions.com/webservice/services/LabcorpOTS/wsdl/LabcorpO TS.wsdl
    I am attempting to call the following method registerDonor(java.lang.String, java.lang.String, com.labcorp.ots.ws.data.CreateRegistrationRequest) which references the CreateRegistrationRequest data element.
    I haven't been successful in creating an instance of the CreateRegistrationRequest class and setting values of its members, as well as the Phone class which is also a data element.
    Any assistance would be greatly appreciated in creating instances of methods located in the targetNamespace="http://data.ws.ots.labcorp.com" of the wsdl.
    Thanks

    Thanks for the explanation and example. At first, I didn't understand what you were getting at, but after reading "Using Top-Level Containers" and "How to Use Root Panes" java tutorials it made much more sense. Unfortunately, the books I've read up to this point, did not cover those topics at all. The books simply stated that the first step in creating a Swing gui was to extend the JFrame, or JApplet, or etc.
    Unfortunately, my original problem persists. I continue to get compile-time errors such as:
    TestUserInterface.java:5: cannot find symbol
    symbol: class UserInterface
    location: class projects.web.TestUserInterface
                          UserInterface ui = new UserInterface(); Anyone know why?
    Both the classes are in the same named packaged. Below is my code:
    package projects.web;
    import java.awt.*;
    import javax.swing.*;
    public class UserInterface extends JFrame{
         JPanel menuPanel = new JPanel();
         JPanel contentPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         JButton save = new JButton("Save");
         JButton addFiles = new JButton("Add");
         public UserInterface(){
         super("File Upload");
         setSize(500, 500);
         menuPanel.add(addFiles);
         selectionPanel.add(save);
         setLayout(new BorderLayout());
         add(menuPanel, BorderLayout.NORTH);
         add(contentPanel, BorderLayout.CENTER);
         add(selectionPanel, BorderLayout.SOUTH);
         } // end constructor
    } // end UserInterface class
    package projects.web;
    public class TestUserInterface{
         public static void main(String[] args){
              UserInterface ui = new UserInterface();
    } // end TestUserInterface class

  • Why portal server can't create an instance of axis.Service class?

    Hi,gurus,
    We developed a uwl custom connector,The time out occured in that custom connector.After adding the time out value from 30s to 300s,the problem still existed.
    The code is like below:
    String endpoint = "http://172.16.127.4:8080/appframe-web/services/WorkItemService";
    Service service = new Service();    // time out code
    Call call = (Call) service.createCall();
    call.setTargetEndpointAddress(endpoint);
    call.setOperationName("wisForPortal");
    call.addParameter("userCode", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);/
    call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
    String temp = "36";
    Object result = call.invoke(new Object[]{temp});
    The time out occured when the portal server create an instance of Service class.Does that mean the server can't find the jars?
    But the object declaration like "Service service=null;" is all right.
    Any ideas?Thanks in advance.

    I have a project called 'Default EAR' in my workspace.
    But I can't add the JAR to the that project. These instructions are for WSAD 4, but I assume WSAD 5 is similar:
    Go to menu File and select Import. Choose "File System" to import from. Specify "Default EAR" as your folder and select the jar file from the directory/browse prompt.
    This is assuming your web app is connected to Default EAR and not some other EAR file. Also once you've done this, you will find that the jar file automatically becomes part of your build path. You didn't have to do anything extra to make that happen.

Maybe you are looking for