How to create an instance of a class which is stored in a String?

I've class name stored in a String Object.
now i've to create an instance of that class name.
How?

This is very dangerous ground because you give up compile-time safety, but you can get a Class object using Class.forName(String). Then you can use methods of the class Class to operate on it (including creating an instance).

Similar Messages

  • How to create an instance of a class which is actually an array?

    the following code gives a runtime exception
    Object obj = (Object )attributeClass.newInstance();
    Exception:
    java.lang.InstantiationException: [Ltest.Name;[/b]
    Here test.Name is user defined class and i want to create an array instance of that class.
    I have tried the following also:
    [b]Object methodArgs[] = new Object[length];
    for(int j=0;j<length;++j){
    methodArgs[j] = singleMemberClass.cast(testArray[j]);
    Object temp = attributeClass.cast(methodArgs);
    In the above code singleMemberClass is test.Name, but the last line gives the following exception.
    java.lang.ClassCastException
    Message was edited by:
    lalit_mangal
    Message was edited by:
    lalit_mangal

    Try the following code
    import java.lang.reflect.Array;
    public class TestReflection {
         public static void main(String args[]) {
              Object array = Array.newInstance(A.class, 3);
              printType(array);
         private static void printType(Object object) {
              Class type = object.getClass();
              if (type.isArray()) {
                   System.out.println("Array of: " + elementType);
              System.out.println("Array size: " + Array.getLength(object));
    class A{
    }

  • How to create an instance of a class?

    how do you create sn instance of a class, and how do you call a method from another class?

    You may need to read thru the information provided on this page to understand how to create objects: http://java.sun.com/docs/books/tutorial/java/data/objectcreation.html
    I'd also suggest you read the tutorial available at: http://java.sun.com/docs/books/tutorial/java/index.html
    Regarding how you call a method belonging to another class you could do it in the foll. ways depending on whether the method is static or not - a static method may be called using the class name followed by a dot and the static method name while a non-static method would require you to create an instance of the class and then use that instance name followed by a dot and the method name. All said and done i'd still suggest you read thru the complete Java programming tutorial to get a good grounding on all these concepts and fundamentals of the language if you are looking to master the technology.
    Thanks
    John Morrison

  • How to create the instance of a class and to use this object remotely

    I have to change a standalone program to do it working on a local net.
    the program is prepared for this adjustment, because the only problem for this change came from the use of the database; and, in the application, all the accesses to the database come from only a class that supplies a connection to the database.
    In this way I think that I could have (in a local net) a "server application" that has the database embedded inside it.
    Furthermore, some client applications (running in different computers of the net) could get access to the database through the connection that comes from an instance of the class that, in the "server application", is made to provide the connection to the database.
    I think this could be a good idea...
    But I don't have practice with distributed applications and I would ask some suggestion about the way to realize my modification.
    (in particular how to get and use, in the "client applications", the instance of the class that give the connection to the database from the "server application").
    I would have some help..
    thank in advance
    regards
    tonyMrsangelo.

    tonyMrsangelo wrote:
    I have to change a standalone program to do it working on a local net.
    the program is prepared for this adjustment, because the only problem for this change came from the use of the database; and, in the application, all the accesses to the database come from only a class that supplies a connection to the database.
    In this way I think that I could have (in a local net) a "server application" that has the database embedded inside it.
    Furthermore, some client applications (running in different computers of the net) could get access to the database through the connection that comes from an instance of the class that, in the "server application", is made to provide the connection to the database.
    I think this could be a good idea... Which is why JEE and implementations of that exist.
    But I don't have practice with distributed applications and I would ask some suggestion about the way to realize my modification.
    (in particular how to get and use, in the "client applications", the instance of the class that give the connection to the database from the "server application").
    You can't pass a connection from a server to a client. Nothing will do that.
    As suggested you can create a simple RMI server/client set up. Or use a more feature rich (and much more complex) JEE container.
    RMI is simple enough for its own tutorial
    [http://java.sun.com/docs/books/tutorial/rmi/index.html]
    JEE (previously called J2EE) is much more complex and requires books. You can get a brief overlook from the following
    [http://java.sun.com/javaee/]

  • 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;
       }

  • How to create an instance of a protected class outside the enclosing packag

    Hi all,
    I have a piece of code like this:
    package test;
    public class A {
    protected class B { }
    How to create an instance of B outside the package test ? Could you please give me an example ?
    Thanks
    Ha Chau

    Thank WirajR for your reply, but in your solution,
    you have to create an instance of B inside class A
    and pass it outside. I would like to know whetherwe
    can create an instance of class B outside thepackage
    test. That means I want the instance creation
    expression of B appears outside the package test.Can
    we do that?
    If you want to use a class this way then it shouldn't
    be marked protected. I can't see why you don't
    just declare it public if that's what it is.
    Wouldn't be much point to haveing a protected
    modifier if it had no effect, would there?I think there is use for it if you use an interface to filter out the parts you want to give public access to, and keep the part you want to keep protected, protected

  • Creating multiple instances of a class in LabVIEW object-oriented programming

    How do you create multiple instances of a class in a loop?  Or am I thinking about this all wrong?
    For instance, I read in a file containing this information:
    Person Name #1
    Person Age #1
    Hobby #1
    Hobby #2
    Hobby #3
    Person Name #2
    Person Age #2
    Hobby #1
    Hobby #2
    Hobby #3
    Person Name #3
    Person Age #3
    Hobby #1
    Hobby #2
    Hobby #3
    If I define a Person class with name, age, and an array of strings (for the hobbies), how can I create several new Person instances in a loop while reading through the text file?
    FYI, new to LabVIEW OOP but familiar with Java OOP.  Thank you!

    First of all, let's get your terminology correct.  You are not creating multiple instances of a class.  You are creating Objects of the class.
    Use autoindexing to create an array of your class type.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • How to create an object of a class?

    plz read the question carefully ..
    how to create the object of a class by giving the class name as an String
    suppose i have a java file name:" java1.java ".
    so now how to create an object of this class "java1"by passing a string "java1"..

    kajbj wrote:
    rajeev-usendi wrote:
    thanks but still i have problem..
    i have created the object but now i m unable to do anything with that created object..
    i have coded like this..
    Object o= Class.forName("java1").new Instance();
    after this i m unable to do anything with the object 'o'..So why did you create the instance? You can also get all methods using reflection, but that is probably not what you want to do. You should instead let the class implement an interface and cast the created object into that interface ans call the methods that you want to call.
    KajI agree with Kaj. If you need to use a class that's unavailable at compile time, you should create an appropriate interface by which to refer to the class and then you create instances reflectively and access them normally via their interface (which is called reflective instantiation with interface access)

  • Creating an instance of a class with no default constructor

    Hello gurus,
    I wrote my own serialization and RMI protocol for both C++ and Java that follows closely what the default Java version does. I'm trying to recreate an object on the Java side that was sent over the wire. The first step is to create an instance of the class. How do I create an instance of a class that has no constructor (i.e. the only instances are static, created by the class itself and returned by static methods) or one that has no default constructor (like Integer)? The Java serialization seems to support it but the reflection API doesn't seem to have any support for this (i.e. Class::newInstance() and Constructor::newInstance()). It seems that through the standard API you can only create an object via one of its constructors. There must be a "hidden" method somewhere that allows the Java serialization to create an object without calling a constructor - where is it?
    Dominique

    There must be a "hidden" method
    somewhere that allows the Java serialization to create
    an object without calling a constructor - where is
    it?You are correct, the way in which the Serialization creates Objects is "hidden" deep within the runtime.
    If it were not hidden, you would be able to find it, and use it to violate the integrity of the VM.

  • 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

  • How to create multiple instance on same database

    Hi ,
    I would like to know how to create multiple instance on same database . I know that some people use database configuration assistant to do this but i could not figure out how they did it.
    Any how if some one can help me with this and can give me links of this it would be great help for me.
    Thank you for reading my problem and helping me !
    Amil
    please if possible mail me on [email protected]

    How to create multiple instance?????Do you mean multiple instances on the same database, or multiple databases on the same machine ?
    I m new to this field....
    Willin to learn a lot about oracle....Then it wouldn't be bad reading a bit of Database Concepts

  • Create an instance of my class variable

    Hello all,
    I'm a newbie to iPhone/iPad programming and am having some trouble, I believe the issue is that I'm not creating an instance of my class variable.  I've got a class that has a setter and a getter, I know about properties but am using setters and getters for the time being.  I've created this class in a View-based application, when I build the program in XCode 3.2.6 everything builds fine.  When I step through the code with the debugger there are no errors but the setters are not storing any values and thus the getters are always returning 0 (it's returning an int value).  I've produced some of the code involved and I was hoping someone could point out to me where my issue is, and if I'm correct about not instantiating my variable, where I should do that.  Thanks so much in advance.
    <p>
    Selection.h
    @interface Selection : NSObject {
      int _choice;
    //Getters
    -(int) Choice;
    //Setters
    -(void) setChoice:(int) input;
    Selection.m
    #import "Selection.h"
    @implementation Selection
    //Getters
    -(int)Choice {
      return _choice;
    //Setter
    -(void)setChoice:(int)input{
              _choice = input;
    RockPaperScissorsViewController.m
    #import "RockPaperScissorsViewController.h"
    @implementation RockPaperScissorsViewController
    @synthesize rockButton, paperButton, scissorsButton, label;
    //@synthesize humanChoice, computerChoice;
    -(void)SetLabel:(NSString *)selection{
              label.text = selection;
    -(IBAction)rockButtonSelected {
    //          [self SetLabel:@"Rock"];
              [humanChoice setChoice:1];
    </p>
    So in the above code it's the [humanChoice setChoice:1] that is not working.  When I step through that portion with the debugger I get no errors but when I call humanChoice.Choice later on in the code I get a zero.
    -NifflerX

    It worked, thank you so much.  I put
    humanChoice = [[Selection alloc]init];
    In viewDidLoad and it worked like a charm.  Thank you again.
    -NifflerX

  • How to create an instance for RemoteSession without using create() method

    How to create an instance for RemoteSession without using create() method?

    What's RemoteSession? Not in the JDK. And does the question have anything to do with concurrency?

  • How to create an instance of the database

    No that won't work. I have to set it up independant from each other because I can't get to Uni until Monday and I want to have this done over the weekend really.
    The main issue seems to be now how to create an instance of the database

    To create a database:
    you first connect as internal (user) with the passeword 'oracle'
    the syntax is: connect internal/oracle
    You type in this script:
    STARTUP NOMOUNT PFILE=$PFILE
    CREATE DATABASE db01
    LOGFILE
    GROUP 1 ('c/oracle/oradata/db01/redo_01a.log',
    'c/oracle/oradata/db01/redo_01b.log'
    ) size 100k,
    GROUP 2 ('c/oracle/oradata/db01/redo_02a.log',
    'c/oracle/oradata/db01/redo_02b.log'
    ) size 100k
    MAXLOGFILES 32
    MAXLOGMEMBERS 2
    MAXLOGHISTORY 1
    DATAFILE 'c/oracle/oradata/db01/system01.dbf'
    size 7M
    MAXDATAFILES 254
    MAXINSTANCES 1;
    This script could be modified to reflect the features you want for your database.
    db01 = the name you can give to your database
    Good luck,
    Henri

  • What is an Instance in application server and how to create an Instance?

    Hi All,
    What is an Instance in application server and how to create an Instance? What is the procedure to get file path from an Instance?
    What is the significance of Instance in ABAP?

    hi
    good
    go through these links,this will gives you complee idea about the creating instances in application serverl.
    http://www.erpgenie.com/sap/basis/
    http://www.sapdevelopment.co.uk/file/file_disall.htm
    thanks
    mrutyun^

Maybe you are looking for

  • Windows movie maker wont work

    hi  I have a w520 with a quadro 1000m graphics card running on windows 7 - im trying to get windows moviemaker to work but keep getting the message saying that my system isn't equipped to do this - ive downloaded the nvidea driver updates and also wi

  • Vertical scroll bar disappears when I minimize the screen

    I have Firefox 10.0.2. I do have a vertical scroll bar with both the up and down button; however, they all disappear when I minimize the screen. When I am in Ancestry, for example, when I minimize I get a horizontal scroll bar but there is no vertica

  • Extended Network Question

    I just bought a Seagate GoFlex media player mainly to use for playing movies from a GoFlex hard drive, but it also has capability to stream Netflix etc, but only via an ethernet connection. I have an AirPort Extreme as my primary router, extended by

  • How to remove several versions of firefox remotely

    I have several versions of firefox, i want to uninstall all of them to install from sccm the last one in all computers. is there a msi or an universal uninstaller? Thans a lot,

  • Z22 change user name

    I purchased a new Z22 to replace my Zire.  When I went through the installation process of my new Z22 via the supplied CD, I entered my user name incorrectly compared to how it is entered on my Zire and my old desktop Palm software.  Therefore the co