Dynamic Creation of Class Name

I just want to create the class name on the fly.
Look the example below.
String className = "gui.Header";
className header = new className;
Let's assume that there is a Header class somewhere.
Is this possible? or is there a way to do this?

From what i understand, u wish to create an instance of a class whose name is known to you at runtime - correct me if i'm wrong - i'll answer based on my assumption. You can basically do that using Reflection in Java. I'm pasting sample code which shows how you do this:
The following sample program creates an instance of the Rectangle class using the no-argument constructor by calling the newInstance method:
import java.lang.reflect.*;
import java.awt.*;
class SampleNoArg {
public static void main(String[] args) {
Rectangle r = (Rectangle) createObject("java.awt.Rectangle");
System.out.println(r.toString());
static Object createObject(String className) {
Object object = null;
try {
Class classDefinition = Class.forName(className);
object = classDefinition.newInstance();
} catch (InstantiationException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
return object;
Hope the above helps.
John Morrison

Similar Messages

  • Dynamic creation of class at runtime

    I need to be able to dynamically create an instance of a
    class that isn't known until runtime - actually based on the
    filename
    so in my fla:
    var className:String="Test"; /* code to get a class name
    derived from the filename */
    var obj = new [className]();
    trace(obj);
    the code above only works if i put the literal directly in [
    like so:
    var obj = new ["Test"]();
    is there a way to do this???
    Any help much appreciated
    cheers Steve

    This might help you out:
    http://dynamicflash.com/2005/03/class-finder/
    "steveanson" <[email protected]> wrote in
    message
    news:e3fcnv$6c7$[email protected]..
    > I need to be able to dynamically create an instance of a
    class that isn't
    known
    > until runtime - actually based on the filename
    >
    > so in my fla:
    > var className:String="Test"; /* code to get a class name
    derived from
    the
    > filename */
    > var obj = new ();
    > trace(obj);
    >
    > the code above only works if i put the literal directly
    in
    > like so:
    > var obj = new ();
    >
    > is there a way to do this???
    > Any help much appreciated
    > cheers Steve
    >
    >
    >

  • Dynamic creation of classes

    hi there
    i was wondering if it was possible to create an instance of a
    class (AS 2.0) at runtime, given just a string value for the class
    name
    eg, my first attempt was something like
    var class_str:String = "MyClass1";
    var inst
    bject = new eval(class_str)();
    now, "eval(class_str)" returns an object of type "function",
    ie the function reference to the class constructor, and so all i
    get is a new "function object"
    any clues, or am i p***ing in the wind?
    tia
    bhu

    I'm afraid "eval()" can't be used this way:
    LiveDocs

  • Dynamic creation of class objects?

    I have a requirement where in at runtime I would know the class name, method name, properties, interface..and coding lines to be put into a method?
    Can anyone suggest a way to create the consumable central class object with these details, activate it and without any manual intervention create this object in backend?

    From other thread...use SEO* package

  • Dynamic display of class name

    I have already posted this problem in the "New To java" forum but then considered that it might be more complicated than I expected. Problem is I am trying to construct a toString method that displays the class name but I wish to be able to extend the class and override the toString method. Then the overridden method must display the new class name. I have a feeling that I need to make a separate method to do this but I just can�t get my head around how to get the class name without hard coding it.

    Please don't crosspost. It cuts down on the effectiveness of responses, leads to people wasting their time answering what others have already answered, makes for difficult discussion, and is generally just annoying and bad form.

  • Help with dynamic creation of class object names

    Hi all
    Wonder if you can help. I have a class player.java. I want to be able to create objects from this class depending on a int counter variable.
    So, for example,
    int counter = 1;
    Player p+counter = new Player ("Sam","Smith");the counter increments by 1 each time the method this sits within is called. The syntax for Player name creation is incorrect. What I am looking to create is Player p1, Player p2, Player p3.... depending on value of i.
    Basically I think this is just a question of syntax, but I can't quite get there.
    Please help if you can.
    Thanks.
    Sam

    here is the method:
    //add member
      public void addMember() {
        String output,firstName,secondName,address1,address2,phoneNumberAsString;
        long phoneNumber;
        boolean isMember=true;
        this.memberCounter++;
        Player temp;
        //create HashMap
        HashMap memberList = new HashMap();
        output="Squash Court Booking System \n";
        output=output+"Enter Details \n\n";
        firstName=askUser("Enter First Name: ");
        secondName=askUser("Enter Second Name: ");
        address1=askUser("Enter Street Name and Number: ");
        address2=askUser("Enter Town: ");
        phoneNumberAsString=askUser("Enter Phone Number: ");
        phoneNumber=Long.parseLong(phoneNumberAsString);
        Player p = new Player(firstName,secondName,address1,address2,phoneNumber,isMember);
        //place member into HashMap
        memberList.put(new Integer(memberCounter),p);
        //JOptionPane.showMessageDialog(null,"Membercounter="+memberCounter,"Test",JOptionPane.INFORMATION_MESSAGE);
        //create iterator
        Iterator members = memberList.values().iterator();
        //create output
        output="";
        while(members.hasNext()) {
          temp = (Player)members.next();
          output=output + temp.getFirstName() + " ";
          output=output + temp.getSecondName() + "\n";
          output=output + temp.getAddress1() + "\n";
          output=output + temp.getAddress2() + "\n";
          output= output + temp.getPhoneNumber() + "\n";
          output= output + temp.getIsMember();
        //display message
        JOptionPane.showMessageDialog(null,output,"Member Listings",JOptionPane.INFORMATION_MESSAGE);
      }//end addMemberOn running this, no matter how many details are input, the HashMap only gives me the first one back....
    Any ideas?
    Sam

  • Dynamic creation of object names

    Dear all,
    I have chose a rather generic title for a rather special problem, since I believe the above is the root. I am trying to create a bunch of JButtons which should have a running number in their names, like: button1, button2, button3, etc. Naturally, I'd like to do this in a loop. But it seems like I can't just concatenate the loop index to the button name like this:
    for(int i = 0; i < x; i++)
          JButton myButton + i = new JButton("Text");
        }How else could I achieve this? Thanks a lot in advance for any hitns!
    Cheers,
    N.

    Sorry for checking back so late...got distracted.
    To clarify further: I want to populate a column in a JTable with the buttons. The table rows contain pairs of words for a simple vocabulary trainer. If the user clicks on the button, the respective row should be deleted. The table data is built in a loop that populates a 2-dimensional object array. So, the buttons need some sort of identifier associated with them, so that I can determine which row should be deleted.
    Cheers,
    N.

  • Dynamic creation of class and calling methods

    I've got and interface called Transformation and then two implementations called TxA and TxB, where TxA and TxB have their own attribtues and setter and getters for these attributes.
    The question is, I need to create instances of TxA and TxB and called the setter and getters where I at runtime I only know the attribute to set, how can I create and instance and call the right getters and setters methods?
    Thanks in advance

    Smart money says your design sucks and needs to be rethought entirely. Can we get specifics?
    Drake

  • Dynamiclally retreiving the main class name

    Hi Folks,
    I would like to dynamically retrieve the class name of the main class which was invoked. Lets say my class name is HelloWorld. I run it using
    java HelloWorld
    Now I need to dynamically retrieve the Classname (HelloWorld) using a java program. Can any please let me know how to achieve it.
    Regards,
    PA

    georgemc wrote:
    Someone else asked this very recently, but I'm bugggered if I can remember the answer. Well, the most common answer was "Why d'you need to do this?" but someone actually knew how to do it. I think it involved the instrumentation API, but I might be wrong. Pretty sure it wasn't anything to do with reflection, thoughYou are just soooooooooooooo sarcastic, George! I am gonna get one of the moderators out after you ... so watch your step! Regards,
    ~Bill

  • AS3 - dynamic class names with *new* operator

    I'm using AcrtionScript 3 and Adobe Flash 9 Public Alpha.
    I have 50 movie clips in the Library that use Linkage to set
    the Class name to: Img1, Img2, Img3, ..., Img50.
    I have a parent class named RandImg. I want the constructor
    for RandImg to randomly select one of the 50 movie clips from the
    Library and display it. I could get this working by generating a
    random number, and then writing a really huge switch statement to
    associate each possible random number with its respective Library
    Movie Clip Class name, but I would much rather do this with a
    dynamic/variable class name based on the random number, such as:
    var nImgChoice:Number = Math.floor( Math.random( ) * 50 ) +
    1;
    var mcImg:MovieClip = new [ "Img"+String(nImgChoice) ] ( );
    addChild( mcImg );
    Note that this used to be possible in AS 2 by doing the
    following:
    this.attachMovie( "Img"+String(nImgChoice) , "mcImg",
    this.getNextHighestDepth());
    Suggestions?
    Thanks,
    ~JC

    import flash.display.DisplayObject;
    import flash.display.Sprite;
    import flash.utils.getDefinitionByName;
    var nImgChoice:Number = Math.floor( Math.random( ) * 50 ) +
    1;
    var ClassReference:Class =
    getDefinitionByName("Img"+String(nImgChoice) ) as
    Class;
    var instance:Object = new ClassReference();
    addChild(DisplayObject(instance));

  • HOW TO GIVE CLASS NAME DYNAMICALLY???

    Hi all!
    I want to give class name dynamically to my statment
    <jsp:useBean id="myBean" scope="session" class="myPackage.myClass"/>
    now here i want to pass a String as class name how can i do it?
    Jiaa:):):)

    Hi,
    You can't assign dynamically a classname in the instruction jsp:useBean
    S�b

  • How to get the class name and field name dynamically

    Hi
    I have a class (ex: Contract) the fields (ex : a,b,c) .i need to get the class name and field name dynamically
    ex
    if( validation file for the field Contract.a){
    return contract.a;
    }else if(validation file for the field Contract.b){
    return contract.b;
    how to pass the field name and object dynamically
    Please help me .............
    Thanks in Advance..
    Edited by: 849614 on Aug 11, 2011 6:49 AM

    YoungWinston wrote:
    maheshguruswamy wrote:
    Agreed, but IMO, i still feel its best if there is no tie in between consumer class level details and the database it talks to. A service layer is needed in between them.Sounds like you've done a bit of this before. Me, I've either been a modeller/DBA, doling out data, or a nuts and bolts programmer (and actually more toolmaker than apps, but did a bit of that too).
    Do you know of a good book about the "middle ground" (ie, these service layers)? I understand it empirically, but haven't had a lot of exposure to it.
    Winston
    Edited by: YoungWinston on Aug 11, 2011 10:34 PM
    PS: Apologies. Edited my previous post, presumably while you were composing your reply, when I finally realized what '.filed' meant.Most of my work is in web development, never been a DBA :) . The biggest 'concern' in my shop is 'separation of concerns'. The UI group reports up to a different IT head, the DB group reports up to a different IT head and so on. The looser the coupling between these systems, the lesser the project costs (Integration, QA etc) are. Martin Fowler's books contain good information about separation of concerns in an enterprise environment. The two books which i recommend are
    [url http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420]Enterprise Application Architecture and
    [url http://www.amazon.com/Enterprise-Integration-Patterns-Designing-Deploying/dp/0321200683/ref=pd_sim_b_1]Enterprise Integration Patterns

  • Java Core Program :: Dynamic Object Creation for Classe & Invoking the same

    Hi,
    I need to create a dynamic object for a class & invoke it.
    For eg: I have a table in my DB where all the names of my java classes are stored. I need to call name from the table of the DB and call that class dynamically in my java program.
    ResultSet_01 = executeQuery("select classname from class_table where class_descrip = 'Sales Invoice' ");
                   while(ResultSet_01.next())
                        String class_name = ResultSet_01.getDouble("classname");
                   }Now using the string in class_name that is fetched from ResultSet_01, I need to create an object for the class_name & invoke the class that is been created with the same name.
    Thank in advance.
    Regards,
    Haider Imani

    Well for a start since a class name is a String, not a number you'd better start by getting the name with getString() not getDouble().
    You need to work with fully qualified names, (FQNs) like "com.acme.myproject.MyDynamicClass", not just the bare MyDynamicClass.
    The next question is where the .class files for the dynamically loaded classes are stored. If they are part of your normal program code, on the class path, then you can use Class.forName to load the class and return a Class object. If they are in some special place you'll need to create a URLClassLoader and get the Class from that.
    Generally, when you load a class this way, it should implement some known interface, or extend some know abstract class. By placing objects of the dynamic class in a reference to that interface you can use the methods defined in the interface.
    The usual way of getting an instance of a dynamic class is to call newInstance() on the Class object.

  • Class.forName() doesn't take dynamic class name

    String name="";
    String country="";
    String className = name + "_" + language + "_" + country;
    Class thisClass = Dynamicclassload.classLoad(className);
    System.out.println(className);
    Class class1 = Class.forName(className);
    child = (ResourceBundle) class1.newInstance();
    child.setParent( bundle );
    bundle = child;
    System.out.println("I am here");
    As i am passing classname as variable it throws an exception class not found exception.but if we write class name as the parameter of class.forName().it works.i am implementing in j2me
    why this happen? give me solution.

    The following classpackage test;
    public class TestLoad {
        String aString = "This is a Test";
        Integer anInteger = new Integer(42);
        public TestLoad() {
            System.out.println("aString = " + aString + ", anInteger = " + anInteger);
    }works correctly when loaded and instantiated by this class:package test;
    import java.util.logging.Logger;
    public class ExecuteTest {
        public static final Logger log = Logger.getAnonymousLogger();
        public static void main(String[] args) {
            try {
                Class clazz = Class.forName("test.TestLoad");
                TestLoad test = (TestLoad) clazz.newInstance();
            } catch (Exception ex) {
                log.severe(ex.toString());
    }and produces the string "aString = This is a Test, anInteger = 42"
    I used the following version of Java on Windows 2000
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
    Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)

  • Dynamic Creation of Buttons and Actions HELP

    Hi there,
    I have got a problem (or maybe even two) with the dynamic Creation of buttons. The code below creates the buttons.
    My main problem is, that the parameter created for the button's action isn't propagated to the assigned event handler. I get a null, though the name of the parameter in the event handler and the name of the parameter added to the action are the same.
    Could it also be that I'm always using the same action? I.e. does wdThis.wdGetAddElementAction() always return the same action instance? If yes, how can I create individual actions for each button?
    Any help is appreciated!
    Cheers,
    Heiko
    "    for(int i=rootContainer.getChildren().length; i<wdContext.nodeFeature().size();i++)
                   IPrivateVCT_Feature.IFeatureElement featureElement = wdContext.nodeFeature().getFeatureElementAt(i);
                   IWDTray featureTray = (IWDTray) view.createElement(IWDTray.class, featureElement.getName());
                   IWDCaption header = (IWDCaption) view.createElement(IWDCaption.class, featureElement.getName()+"_Header");
                   header.setText(featureElement.getName());
                   featureTray.setHeader(header);
                   featureTray.setExpanded(false);
                   rootContainer.addChild(featureTray);
                   IWDButton button = (IWDButton) view.createElement(IWDButton.class, featureElement.getName()+"_Button_AddElement");
                   IWDAction actionAddElement = wdThis.wdGetAddElementAction();
                   actionAddElement.getActionParameters().addParameter("featureIndex", new Integer(i).toString());
                   button.setOnAction(actionAddElement);
                   button.setText("Add Element");
                   featureTray.addChild(button);

    Hi Heiko,
    You have done everything correctly....except for 1 line
    in the code...
    Replace the following line in your code:
    actionAddElement.getActionParameters().addParameter("featureIndex", new Integer(i).toString());
    Replace the above line with this code:
    button.mappingOfOnAction().addParameter("featureIndex",i);
    Actually in your code, you are not associating the parameter with the button...
    Note that addParameter(...) comes with two signatures: addParameter(String param, String value) and addParameter(String param, int value). You can use any of them based on yuor need.
    Hope it helps,
    Thanks and Regards,
    Vishnu Prasad Hegde

Maybe you are looking for

  • Ipod touch not recognized by older computer.

    Okay, I have an old G4 mac with a limit of 10.4.11 to its operating system. I have an ipod touch which worked just fine with version 9 of Itunes. The ipod touch was wonky so I had the battery replaced and the OS reset. The problem is that they reset

  • Printing to Kodak printer

    Hi I can print my photos from iPad to Kodak c310 printer via the Kodak app ok, but I can print a web page or anything else , how can I resolve this, I think I may need an app but don't know which one if so

  • Why is "fill free space" no longer leaving space for more photos or deleting music when I want to add other things

    My iPhone 4 with iOS 5 update doesn't seem to sync as smoothly as before.  Before it used to allow some space for more photos.  Or if I added a photo album toit would delete some of the "free space" music to make room for what I was adding.  Now it j

  • Finder not working after sleep

    Whenever my macbook pro 13" late 2011 wakes from sleep, finder no longer works, and I cannot shut down. I have to force shut down by holding in the power button, and then boot up again. I'm not a power user, and don't know how to fix the problem. If

  • I cannot select or play music from Ipod touch

    I am unable to select music at all directly from the ipod touch. I can access it thru my car stereo though. What all of a sudden happened?