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.

Similar Messages

  • How can i use a string name as an onject name.please help!

    hi it seems like an easy one but i can not find it anywhere.how can i use the name of a string as a name of an object such as the code(my problem is the code)...
    public void oda(String name1){ 
    String name2=name1+"s";
    String name3=name1+"ss";
    TextArea name1=new TextArea();
    TextArea name2=new TextArea();
    TextArea name3=new TextArea();
    i think my problem is clear but to be sure..
    how can i give a name to an object in my textarea which is already using as a string.
    thank u .

    it get very compilcated to change the name of the object you created. identity is something you don't want to mess with..you can do it by usin reflection, but it will slow down your application and (again) is quite complicated...
    a simple solution (and more object-oriennted) is to create a Wrapper, Decorator, or Extends the class.
    example
    public class MyTextBox{
        private String name = null;
        private boolean value = false;
        private JTextArea txtArea = null;
        public MyTextBox(String name, boolean value){
            txtArea = new JTextArea();
            this.value = value;
            this.isOn = isOn;
        public String getComponentName(){  return name; }
        pubic boolean getComponentValue(){ return value; }
        public JTextArea getTextArea(){ return area; }
    }

  • Dynamic class loading from String name

    Hello all,
    I have a question for dynamic class loading:
    If I have a String variable that represents a class name, how can i use it to make dynamically an object of the class tha the string variable represents?
    For example i have a string like this
    String classname="String";
    Using this i want to make a new String object .
    Can anyone tell me how can i do this(example plz)?

    I have worked out the code and this works fine:
    import java.lang.*;
    class dynamictestname{
         public dynamictestname() {
        public static Class test(String objname){
             try{
             Class theClass = Class.forName(objname);
                 return theClass;
            } catch (ClassNotFoundException e)
                throw new NoClassDefFoundError (e.getMessage());
         public static void main (String [] args){
              String classname="java.lang.String";
              Class thisClass=dynamictestname.test(classname);
              try{
              Object instance = thisClass.newInstance();
              }catch(InstantiationException e){
              }catch(IllegalAccessException ie){
    }The new problem i 've faced is that i can't instatiate a new object by the class i have created.I saw some examples with use of the java.lang.reflect but this class i used with user created classes which have methods that the user wants to run dynamically.
    I just want to make an object from the class and give it a value.
    For example if the object i have created with the
    Object instance = thisClass.newInstance();is an object of java.lang.String class
    how can i do something like this below dynamically from instance object :
    String x="TEST ";
    Thanks for the help..

  • Invoke method dynamically  based on string name.

    In my code i have some 50 odd if else condition:
    if(command.equals("abc"))
    //call abc method
    abc();
    else if(command.equals("xyz"))
    // call xyz();
    and so on........
    now based on command string i need to call a method whose name is identical to command string.
    I have used reflection to do this and it works. But just need to know ,
    is there any other approach available?
    Also, it is better to use reflection or just write 50 if else statements and call each function.
    TIA,
    Sachin

    hey i asked the same question a little while ago and got some
    very good feedback at this thread
    http://forum.java.sun.com/thread.jspa?threadID=646255
    i had written some test code but i cant find it.
    you will be looking for this kind of stuff though
    (this isnt intelligible code)
    Object o = Class.forName("hto");
    Field[] fields = ht.getClass().getDeclaredFields();
    Class class1 = ( fields[1].getType() );
    Class class2 = Class.forName("MyClassName");
    Class[] param = { value.getClass() };
    Object[] invokeParam = { value };
    Class[] prim = { Class.forName("HackThis") };
    Method method = ht.getClass().getMethod("set" + var, param);
    method.invoke(ht, invokeParam);

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

  • Instantiating a custom class through a string

    I asked yesterday how to call a function from an XML file, and I figured out how to make that work using the string-to-function call.
    so in my XML file I have <ITEM CALLBACK="ContactsList">View All</ITEM>, and my TextMenu class parses the XML file and creates my navigatable text menu instance. When enterMenu():String is called, it looks to see if the CALLBACK attribute has a value, and if so it returns it as a String.
    so...
    var callbackFnc:String = textMenu.enterMenu();
    if(callbackFnc != null)
         //here's where my problem is
         var myClass:* = new [callbackFnc]();
    I want to create a new instance of the ContactsList class through my XML file by having CALLBACK="ContactsList" and then using the string "ContactsList" to instantiate this object and add it to the the display list (it extends Sprite).
    The code above currently invokes:
    TypeError: Error #1007: Instantiation attempted on a non-constructor.
        at com.cox::Contacts/::keyHandler()
    How could I use a string of the class name to instantiate and add an instance of that class to the stage?

    To create a class by is string name use this:
    var ClassReference : Class = getDefinitionByName( "STRING NAME OF THE CLASS" ) as Class;
        classInstance = new ClassReference();
    in your case:
    var ClassReference : Class = getDefinitionByName( "ContactsList" ) as Class
    var contactList: *   = new ClassReference();

  • Class using another class access

    I'm sure this is not difficult, but finding the answer has been quite elusive for me. I'd like to start simple. I have two classes, Place and Address that look like this:
    public class Address{
       private String street;
       private String town;
      ...some other address stuff
       public void setStreet(String streetname) {
         this.street = streetname;
    public String getStreet() {
         return this.street;
    ...same f or town and others
    }//end of Address class
    Now I have the Place class:
    public class Place {
       private String name;
       private Address address **here begins my questionsI currently have the private address declaration as:
       private Address address = new Address();1. Is this Address address declaration correct, or should it be different?
    2. Do I, create setAddress and getAddress methods in the Place class, and if so, so they just use the object 'address', i.e. 'return address;' ?
    After I understand how to do these two things, I need help in accessing the address parts, like street and town, from a third class, the PlaceTest class which has a 'main' method.
    Thanks in advance for your help.

    Check out this as a for-instance. Here is a sample Address class
        class Address
            private String street;
            private String town;
            private String state;
            private String zip;
            public Address(String street, String town, String state, String zip)
                this.street = street;
                this.town = town;
                this.state = state;
                this.zip = zip;
            public void setStreet(String street)
                this.street = street;
            public String getStreet()
                return street;
            @Override
            public String toString()
                return street + ", " + town + ", " + state + ", " + zip;
        }And here is a Place2 class that uses Address
    class Place2
        private Address address;
        public Place2() {}
        public Place2(Address address)  // <== **** here I'm passing an addresss param
            this.address = address;
        public void setAddress(Address address) // <== **** and here too
            this.address = address;
        @Override
        public String toString()
            return address.toString();
        public static void main(String[] args)
            Place2 myPlace = new Place2(
                new Place2().new Address("100 Main St", "AnyTown", "IL", "60022"));
            System.out.println("My address is: " + myPlace);
            // let's change the address:
            Address address2 = new Place2().new Address("123 First St", "Podunckville", "State of Confusion", "10101");
            // then pass this address to myPlace
            myPlace.setAddress(address2);
            // then show it
            System.out.println("My new address is: " + myPlace);
    }

  • Invoke a method by getting method name from properties object

    HI ,
    I am storing method names in a properties file . Can any one tell me , how can I invoke those methods ?? Please Urgent.
    Here is the sample program what I am trying to do . Please tell me how to invoke method which is represented by the String "methodTobeInvoked" in the below program.
    public class HelloWorld {
         private String name="meena";
         public String getName() {
              return name;
         public void setName(String name) {
              this.name = name;
         public static void main(String[] args) {
              try {
                   Properties props=new Properties();
                   props.setProperty("method", "getName()");
              String methodTobeInvoked= props.getProperty("method");
              }catch (Exception ioe) {
                   System.err.println(ioe.getMessage());
    Thanks!!!

    meenaalenoor wrote:
    I am storing method names in a properties file . Can any one tell me , how can I invoke those methods?
    Here is the sample program what I am trying to do.
    Please tell me how to invoke method which is represented by the String "methodTobeInvoked" in the below program.
    public class HelloWorld {
         private String name="meena";
         public String getName() {
              return name;
         public void setName(String name) {
              this.name = name;
         public static void main(String[] args) {
              try {
                   Properties props=new Properties();
                   props.setProperty("method", "getName()");
              String methodTobeInvoked= props.getProperty("method");
              }catch (Exception ioe) {
                   System.err.println(ioe.getMessage());
    }Have you looked at [java.lang.reflect|http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/package-summary.html] ?

  • Did the Java Writers Get a Little Happy with Memory Use in String class?

    I mean that question half jokingly.
    Taking a look at the String class code, I saw the following (below).
    Why is there an int for offset and an int for count?
    String is immutable, why not just return value.length for the count?
    And what is the offset for?
    Thanks!
    public final class String
        implements java.io.Serializable, Comparable<String>, CharSequence
        /** The value is used for character storage. */
        private final char value[];
        /** The offset is the first index of the storage that is used. */
        private final int offset;
        /** The count is the number of characters in the String. */
        private final int count;
        /** Cache the hash code for the string */
        private int hash; // Default to 0PS: a second look kinda verifies it too.
    in the constructor ,count is even defined as value.length.
        public String(char value[]) {
         int size = value.length;
         this.offset = 0;
         this.count = size;
         this.value = Arrays.copyOf(value, size);
        }

    You don't get the choice. The arrays are shared
    whenever you do substring.Yea, thats my point. I think most Strings are unique.
    Id be very surprised if even 2% of all String use was
    a result of a substring.The wrapper classes use it for parsing.
    File uses it for getName and getParent.
    String uses it for trim.
    Class uses it for resolving names.
    Regex uses it.
    etc. ...
    Now, I don't know what percentage of usage all that amounts to, but it IS heavily used.
    So your desire to gain the 2 bytes back would cost enough byte every time substring is used that it might end up costing far more than the 8 bytes you save.

  • Name and int using a String

    Hi everybody,
    ive got a class that creates a new int. i want the name of the int to be a parameter that i can send into the class. so for example:
    public testObject(String intName)
    then in my main I could say:
    testObject grader = new testObject(gradeOne);
    and the testObject class would make a new int called gradeOne.
    does anybody know how i could accomplish this?

    Well you can hava a java.util.Map that maps Strings (for the names) to Integers (for the values).
    You could encapsulate that map within another class if you feel that helps the design, and provide a method that expresses the relationship pretty easily, e.g.,:
    public class NamedInts {
      private Map mapping = new HashMap();
      public void addNumber(String name, int value) {
        mapping.put(name, Integer.valueOf(value));
      // other methods, presumably, as well
    }Is that what you meant?

  • Can substitution strings be used for table name references?

    Hi,
    I was wondering if it's possible to use substituion strings for table names in SQL queries. This would allow for me to edit all references to a table at one location. For instance, if a table name or dblink changed, I could edit the substitution string or application item to ensure all the queries reference the new table.
    For example:
    select * from &table1.
    table1 would be the substitution string for the actual table name
    I know this is possible if I used a pl/sql function returning a query, but I would much rather use a substition string in a SQL query.
    Thanks in advance.
    Brian

    i think not
    because how create the fields of * in this case
    in the other because all is dynamic, i think that you obtain only an error

  • Dynamically instantiating objects using string name

    Hello to all.
    This is probably an easy question, but I am wondering how I can dynamically create instances of an object in a loop using a string variable as the name.
    The idea here is this:
                   while (someBooleanVariable) {
                        int count = 1;
    String objectName = "myObject" + count;
                        myObject objectName = new myObject; // How do I pass the objectName String variable as a name?
                        count++;
                   } // End while
    Of course this doesn't work - incompatible types, but the idea is that the code would create "myObject1," "myObject2," "myObject3," "myObject4," etc as long as someBooleanVariable = true using the objectName String variable.
    I am new to this and appreciate any help and ideas.
    Thanks!

    BigDaddyLoveHandles wrote:
    There's been this outbreak of people wanting to dynamically name their variables -- is this some sort of scripting disease?It's always been around. Shoot, I remember suffering from it when I first started out, because it seems so, hm I dunno, necessary at the time. Eventually the newbie (me) realizes that the variable "name" means nothing, that reference is everything.
    ... and then I discovered maps, and names were useful again. :o)

  • How do I prompt a user to enter in a string name and set it so it can be used as an input for a DLL

    I was having problems entering in a string name and setting it. Any suggestions.

    Entering the string is easy. Just use a string control.
    To setup the Call Library Function, right click on it and select Configure. Type in the path to the DLL (or use the Browse function) and then use the Function Name dropdown box to select the function within the DLL. From here, you have to setup the parameters. The return type parameter should already be selected in the Parameter drop down box, so click on the Type drop down box and select the type of parameter that the selected function will return. From there, click on the Add Parameter After button to add an input parameter and then select the type of parameter. Continue doing this for all of the input parameters to the DLL. For strings you'll see a new drop down box appear for String Format. Choose the
    format that the DLL expects.
    You need to know what the DLL is looking for. Have fun with it.
    Rob

  • Compile error when using a class by fully-qualified name

    Hi... Is it an AS3 "feature" or a FB compiler bug that I cannot use a class without importing it?
    I have a statement such as
    if (de.codebank.util.StringUtilities.startsWith(status.name, phase.name+"_"))
    which does not compile until I import the StringUtilities class, which is pointless, of course.
    The compile error mentions an unknown property "util"

    I believe this is how AS3 works. Fully qualified class types require import statement.
    You use fully qualified name whenever you want to avoid ambiguity.
    However, when the code is like,
    import mx.collections.XMLListCollection;
    var arr:mx.collections.ArrayCollection;
    It works since compiler now understands that "mx.collections" is a package.

  • How to reference the Instance name using Substitution string or SQL

    All:
    We have an Application that will be replicated in multiple Apex instances and would like to display the current Oracle Apex Instance name ( Similar to the &APP_USER. on the Welcome portion of the page ) .
    Is there a substitution string for this ?
    We plan on using a Show/Hide region on the splash page titled [About], that when clicked displays an HTML region with the subsitution strings.
    If no substitution strings, can someone help with an SQL that returns the Instance name ?
    Thanks for all the help.
    Aubrey Fernandes

    Aubrey Fernandes wrote:
    I currently have 3 URLs to get to my Development, QA and Production servers & will have many more production servers with different Application Ids.
    Development = http://canqa101:7777/pls/ngcrmd01/apex
    QA = http://canqa101:7777/pls/ngcrmq01/f?p=100:1
    Production = http://cancs105:7777/pls/ngcrmp01/f?p=100:1
    What I need are the portions before the final forward slash ( canqa101:7777/pls/ngcrmd01 ) which I assumed is the Oracle Apex instance.That information is determined by the web server configuration (e.g. the DADs when using OHS) rather than through APEX itself. There are no built-in substitution strings for this. Create an application item and an On New Instance (new session) computation to set the value using the function<tt>owa_util.get_cgi_env</tt> function to get the CGI environment variables <tt> HTTP_HOST</tt> and <tt>SCRIPT_NAME</tt>. You can then reference the value in the region using substitution string syntax.

Maybe you are looking for

  • Exchange 2010 , Windows 2008 R2 and framework 3.5 SP1

    Hi all , I have questation about protection exchange server 2010 with framework 3.51 SP1 running in the windows 2008r2 serveru . The DPM server is instaled in the windows 2012r2 server and supported version in this os is 2012R2 RU5 . After install i

  • Metadata field for "file type"?

    I'm trying to find a way to sort images in A3's List view, and I can't seem to find a way to use the "File Type." I know I can filter images, but that's not what I want to do. I'd like to be able to have file type as a column so I can sort and have,

  • Can't import some MP3s into Centrale

    $Can't import some MP3s into Centrale?I've been using Centrale with my X-Fi for a couple of years and have managed to tag and import 000s of mp3s wothout problem. I recently downloaded 2 series of podcasts from Absoluteradio and despite all attempts,

  • Animating a line by moving bezier handles, points

    I'm working on a clip that simply moves lines around the stage and makes them bend. It seems very easy to do this, in a sloppy and uncontrolled kind of way, with the record button on, moving to different points along the timeline and moving the handl

  • System copy with Export/Import Distribyted system UNIX database, Windows CI

    HI we have a distributed system witch I want to make a copy of Oracle Database on HP-UX CI + SCS on Windows Dual stack system  ABAP/Java 1)  I have made an system copy with data base copy tools, and that works fine. 2)  I have made a system copy expo