Making an instance of a class using a String???Help!

Hello,
If have a problem.
I have to make a method in which you put a string . This method must make an instance of a
class, whose the name is specified in that String.
How do I do that?

private UrClass getAClass( String classname ) throws Exception
     return UrClass urass      = (UrClass)(Class.forName( classname ).newInstance();
or
private UrClass getAClass( String classname )
     try {
          return UrClass urass      = (UrClass)(Class.forName( classname ).newInstance();
     } catch ( Exception e ) {
          return null
is it enough?
[email protected]

Similar Messages

  • How can you create an instance of a class using ClassLoader given only

    the class name as a String. I have the code below in the try block.
    Class myTest = this.getClass().getClassLoader().loadClass("Testclass");
    Object obj = myTest.newInstance();
    String className = obj.getClass().getName();I don't want to typecast the class like
    Testclass obj = (TestClass) myTest.newInstance();I want to be able to create the classs at runtime and then get the methods in the class and execute those methods. Can it be done without having to code the typecasting in before compile time?

    I read on the web of people creating objects from interfacesDoesn't sound like the thing to do... Theoretically you could create dummy classes on the fly that implement some interface, but that's not very useful.
    Sounds like you are trying to load classes and execute them via interfaces. Like this:
         Class clazz = Class.forName("java.util.LinkedList");
         Collection c = (Collection) clazz.newInstance();
         c.add("hello");
         c.add("world");
         System.out.println(Arrays.toString(c.toArray()));LinkedList is the class, Collection is the interface which LinkedList implements. You can then call the methods declared in the interface. The interface gets "compiled in" into the program and the classes that implement it get loaded whenever and from wherever you load them.
    You could also use reflection to call methods without an interface, but that is type-unsafe, inelegant, hackish, and just plain ugly.

  • Invoking a class using a string name

    I have a class called GPSSinglePoint
    If I have the following String object...
    String myClass = "GPSSinglePoint";
    how do I instantiate the class?
    BTW, can I instantiate GPSSInglePoint as a thread if it implements Runnable?
    Thank you in advance.
    Edited by: sidkdbl07 on Apr 3, 2008 2:55 PM

    Encephalopathic wrote:
    masijade. wrote:
    .....But, if you need to ask, and don't have any one there who can sit down with you physically and tutor you on it (and the reasons why you normally should not use it), then you probably shouldn't be attempting this yet.Agree 100%. The first question I'd be asking you is why you would want to implement things this way as there are usually (although I'll grant you, not always) better ways to go about doing this.I agree somewhat - specifically I don't like using reflection for looking up methods. However, using Class.forName can be very handy when you have multiple alternative implementations of the same interface, e.g. for game search methods. In this case, it gives you an (almost) free plugin architecture.

  • I am making a movie on my ipad using iMovie, need help with music.

    I have a song that I put into my itunes library and then uploaded it into a dropbox folder.  I have dropbox on all my apple products.  Anyway, I would like to use this song in my imovie project.  How do I get it into imovie from dropbox.  It is a an aif. file.
    THANKS!  Kelly

    What you share on iTunes file share is the project itself, not the final video. Press share > camera roll. And then you can access the video on explorer/finder as any other photo.

  • Creating instances using a string identifier

    Is there a way to create an instance of a class given it's
    class name as a string( for example). I know I could do it simply
    by using conditional logic, but I'd like this to be extensible and
    don't want to have to keep adding conditions as the system grows.
    In other languages I've used, this is possible in many ways
    and was wondering if there is a way to do this in AS 3.0
    Thanks.

    Thanks for the heads up Ed!
    One way to be ableto get around your issue (not that this
    exists in AS 3.0) is to be able to "register" a class so the
    compiler/linker can link it into the swf and you get compile time
    checking.
    This is the way Delphi allows for this. The C# complier is
    kind of in between in that you are still liable to get a runtime
    error in the case that you creat an instance of a class using (say)
    Activator.CreateInstance() which is the equivalent.
    One way to get around this in AS 3.0 (I think) would be to
    simply declare a variables of the types you intend to create
    instances of dynamically. This should force the linker to link in
    the class definition.
    Of course in both C# and Delphi you can create instances of
    classes unknown to you at complie time. From the looks of it, AS
    3.0 can't do this.

  • How to create a group and add class instances to that group using VSAE

    how can i create a group in VSAE and add the objects to the group that too instances of a class.
    should i use the ID of the object or some other rule to add members to that group
    Thanks & Regards, Suresh Gaddam

    Hi,
    The below links should be helpful for you to create group in VSAE:
    Computer and Instance Group Fragments in VSAE
    http://blog.scomskills.com/create-a-computer-or-instance-group/
    Create a Group of Health Service Watcher Objects Using VSAE
    http://blog.scomskills.com/create-a-group-of-health-service-watcher-objects-using-vsae/
    SCOM VSAE – Custom Dynamic Computer Groups Based On Server Registry Keys
    Regards,
    Yan Li
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected]

  • 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/]

  • Singleton Class using a constructor not a get Instance method ?

    Hi,
    I have a class with a couple of contructors, the class is instantiated many times in the application.
    Is there any way by which I can return a single instance of the class when the contructor is called ?.
    I dont want to declare a get instance method to return a single instance is it somehow possible to do this in the contructor itself.
    This is done so I dont have to refactor the whole application and change all the places where this class is instantiated.
    Example
    XXXClass xxx = new XXXClass();
    every time new XXXClass() is called the single instance of the class must be returned.
    I dont want to implement
    XXXClass xxx = XXXClass.getInstance();
    Thanks in advance
    Rgds
    Pradeep Thomas

    Pradeep ,
    You see a constructor does not return anything
    when you tell java
    String str = new String();
    It is into the reference str that a Object of the type String is assigned and used ..
    If you want a single instance to exist in your application ..the best way is to use the singelton approach.
    Alternatively you could create one static instance of the object in a parent class and all the classes that inherit from it will then share access .

  • I'm making a DVD for our class reunion.  A fellow classmate has some video on a mini cassette that he said he could put on a dvd.  Will I be able to import from that dvd to imovie to use in my dvd?

    I'm making a DVD for our class reunion.  A fellow classmate has some video on a mini cassette that he said he could put on a dvd.  Will I be able to import from that dvd to imovie to use in my dvd?  Or does it have to be in another format, maybe flash drive? 

    Ask your friend to supply you the DVD as a data DVD using either DV or AIC as the video format, burning the DVD as a DVD for a DVD player will degrade the video quality.

  • What is the difference between instance variable and class variable?

    i've looked it up on a few pages and i'm still struggling a bit maybe one of you guys could "dumb" it down for me or give and example of how their uses differ.
    thanks a lot

    Instance is variable, class is an object.What? "Instance" doesn't necessarily refer to variables, and although it's true that instances of Class are objects, it's not clear if that's what you meant, or how it's relevant.
    if you declare one instance in a class that instance
    should be sharing within that class only.Sharing with what? Non-static fields are not shared at all. Sharing which instance? What are you talking about?
    if you declare one class object it will share
    anywhere in the current program.Err...you can create global variables in Java, more or less, by making them static fields. If that's what you meant. It's not a very good practice though.
    Static fields, methods, and classes are not necessarily object types. One can have a static primitive field.

  • How can I write an instance of a class in a static variable

    Hi !
    I have an instance of a class
    Devisen dev = new Devisen();
    In an other class I have a static method and I need there the content of some variables from dev.
    public static void abc()
    { String text=dev.textfield.getText()
    I get the errormessage, that the I cannot use the Not-static variable dev in a static variable.
    I understand that I cannot reference to the class Devisen because Devisen is not static I so I had to reference to an instance. But an instance is the same as a class with static methodes. (I think so)
    Is there a possibility, if I am in a static method, to call the content of a JTextField of an instance of a class ?
    Thank you Wolfgang

    Hallo, here is more code for my problem:
    class Login {
       Devisen dev=new Devisen();
    class Devisen {
       JTextField field2;
       if (!Check.check_field2()) return; // if value not okay than return
    class Check {
       public static void check_field2()
         HOW TO GET THE CONTENT OF field2 HERE ?
    One solution ist to give the instance to the static function, with the keyword "this"
    if (!Check.check_field2(this)) return;and get the instance
    public static void check_field2(Devisen dev)BUT is that a problem for memory to give every method an instance of the class ? I have 50 fields to control and I dont want do give every check_method an instance of Devisen, if this is a problem for performance.
    Or do I only give the place where the existing instance is.
    Hmm...?
    Thank you Wolfgang

  • How to call a instance method without creating the instance of a class

    class ...EXCH_PRD_VERT_NN_MODEL definition
    public section.
      methods CONSTRUCTOR
        importing
          value(I_ALV_RECORDS) type ..../EXCH_VBEL_TT_ALV
          value(I_HEADER) type EDIDC .
      methods QUERY
        importing
          I_IDEX type FLAG
          i_..........
        returning
          value(R_RESULTS) type .../EXCH_VBEL_TT_ALV .
    Both methods are instance methods.
    But in my program i cannot created instance of the class unless i get the results from Query.
    I proposed that Query must be static, and once we get results we can create object of the class by pasing the result table which we get from method query.
    But i must not change the method Query to a static method.
    Is there any way out other than making method Query as static ?
    Regards.

    You can't execute any instance method without creating instance of the class.
    In your scenario, if you don't want to process your method of your class, you can check the instance has been created or not.
    Like:
    IF IT_QUERY IS NOT INITIAL.
      CRATE OBJECT O_QUERY EXPORTING......
    ENDIF.
    IF O_QUERY IS NOT INITIAL.
    CALL METHOD O_QUERY->QUERY EXPORTING....
    ENDIF.
    Regards,
    Naimesh Patel

  • Create multiple instances of same class but with unique names

    Hi,
    I'm creating an IM application in Java.
    So far I can click on a user and create a chat session, using my chatWindow class. But this means I can only create one chatWindow class, called 'chat'. How can I get the application to dynamically make new instances of this class with unique names, for examples chatWindowUser1, chatWindowUser2.
    Below is some code utlising the Openfire Smack API but hopefully the principle is the clear.
        private void chatButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
            int selectedUserIndex = rosterList.getSelectedIndex();
            String selectedUser = rostAry[selectedUserIndex].getUser();
            System.out.println("Chat with: " + selectedUser);
            if (chatBox == null) {
                JFrame mainFrame = CommsTestApp.getApplication().getMainFrame();
                chatBox = new CommsTestChatBox(mainFrame,conn,selectedUser);
                chatBox.setLocationRelativeTo(mainFrame);
            CommsTestApp.getApplication().show(chatBox);
    }  

    yes, an array would work fine, just realize that by using an array, you're setting an upper bound on the number of windows you can have open.
    As for unique names, if you mean unique variable name, you don't need one. The array index serves to uniquely identify each instance. If you mean unique title for the window, set that however you want (username, index in array, randomly generated string, etc.). It's just a property of the window object.

  • Creating a Set  containing instances of another Class, which type?

    Hi All,
    I'm stuck trying to create a set which contains instances of another Class.
    When I created my instance method, it takes an argument which is the instance of another Class.
    It errors as I've used the Class as the type rather than String> or Integer.
    Can someone point my in the right direction?
    WebPageData wpd1 = new WebPageData("this is a sentence for a test", "www.test.com");
    WebPageData wpd2 = new WebPageData("this sentence is shorter", "www.short.com");
    WebPageData wpd3 = new WebPageData("this is very short", "www.very.com");
    Finder f1 = new Finder();
    f1.addsite(wpd1);
    f1.addsite(wpd2);
    f1.addsite(wpd3);
    f1.searchFor("a sentence test");
    Edited by: geedoubleu on Mar 16, 2008 9:03 AM

    The error message is "Semantic error: line 5. Message addsite( WebPageData ) not understood by class'Finder'"
    * Adds the argument of WebPageData instances to to a collection scannedSites.
    public void addSite(WebPageData theWebPage)
    this.scannedSites.add(theWebPage);
    }

  • How to deal with the old instances of any class?

    Hi,
    I have a doubt regarding the old instances of any class. Currently i am designing a game in java swing. I have a new game button, which creates a new game instance of the game class. There might be conditions that the old game is finished and user has clicked for new game button. The old game instance is no more useful for me. In fact that old instance must be deleted from the memory and a new instance should reside in the memory until user again proceed for a new game.
    I want to ask that how to destroy old instances of any class?
    Thank you.

    rp0428 wrote:
    All you can do is remove any reference to it:
    myGame = null;If that was the last reference then it will be eligible for garbage collection and it MAY be collected.And note that there's rarely a good reason to do this. In most cases, simply letting things go out of scope when the method that uses them ends is sufficient. About the only time you need to explicitly set something to null like this is, for example, if you're implementing a collection class and you want to remove an entry.

Maybe you are looking for

  • I can´t donwgrade my icloud storage plan

    Hello, I bought a new storage plan for my phone, but it never worked, I could never back up my phone to my iCloud! And yes I followed all the instructions on your site, like plugging to a source and connecting with the Wi-Fi network. Besides all of t

  • I can't Install Windows 7,8,8.1 using bootCamp Please Help

    I am using macbook pro intel i5 2.4 GHz cpu 13 inch  late 2011 MODEL,I can't install windows 7,8,8.1 using bootcamp,because windows install disk creator option not available in my boot camp Assisstant app,so i can't install windows from USB Pendrive

  • Nikon RAW Files turn purple (while JPEGs unchanged)

    Only recently, not sure if it coincided with an update, my MacBook mis-converts most, but seemingly not all, Nikon (from a D7000) RAW files.  It appears to do it in iPhoto and also in the browser, although all of the thumbnails and JPEGs look correct

  • Text spacing/shifting in Flash CS4?

    Hey guys, I am new to the forum, I have used Flash MX 2004 for quite a while and had never had this problem, recently I gave my site a "facelift" in CS4 and I got it exactly how I wanted it, I exported the swf file and then saved the flash file. That

  • 2010 Nano 'Kills' right headphone/earbud?

    I was in Paris the other day and after finishing up my work I grabbed my iPod Nano and Sony head phones to go out for a stroll.  I barely got through the first song and hadn't even left the hotel yet and the right earphone in the Sonys stoppped worki