Generate variable name from a String

I've got a String "MyVariable" and I need to reference a static variable named MyStaticClass.MyVariable. How do you turn a String into a variable name?

You can't easily do it... you can using reflection:
MyStaticClass.class.getField().getXXX("MyVariable") //depending on what type the field is...But this seems like it may be a flawed design. Maybe you should try making a static HashMap in the class, use a Static init block and static get/set methods:
public class StaticClass
    static Map properties;
    static
        properties = new HashMap();
        properties.put("MyVariable", "Some Value");
        properties.put("OtherVariable", new Integer(3));
    public static Object get(String property)
        return properties.get(property);
    public static void set(String property, Object value)
        //Maybe some code checking to make sure object is right type
        //or don't use a set method at all to make the properties immutable
        properties.put(property, value);
}

Similar Messages

  • How to generate a variable-name from a string

    I want to name some variables automaticly. The names are read from an ArrayList and converted to string.
    I tried it this way, but I failed.
    for(int m=0; m<tags.size(); m++){
         System.out.println("javax.swing.JRadioButton "+tags.get(m).toString().toLowerCase()+"RadioButton;");
         String temp = tags.get(m).toString().toLowerCase().concat("RadioButton");
         javax.swing.JRadioButton temp.toString() = new JRadioButton();
         buttonList.add(m, temp.toString());
    Can anyone help me, please?!

    Because of the Exception I printed the content of temp and of hsh.get(temp) and both are not null:
    temp: authorRadioButton
    hsh.get(temp)): javax.swing.JRadioButton[,0,0,0x0,invalid,layout=javax.swing.OverlayLayout,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@7dd60e50,flags=1184,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,right=2],paintBorder=false,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=]
    So I really don't know why this Exception occurs when trying to use the hsh.get(temp)-method.

  • Making generated variable names?

    Hey, I'm trying to make new Vector variables given some input I already have. I'm doing it as follows:
    for (int i=0; i < commandName.size()-1; i++) {
    String newVariableName = commandName.elementAt(i).toString();
    Vector newVariableName = new Vector();
    Of course, it's not working - but do you know if it is possible to generate variable names in this manner?

    Use HashMap.
    You will generally find that most languages that offer variable dereferencing are also essentially "typeless", although you can sometimes query what the type of the "value" of a variable is.
    HashMap does this exactly, with the bonus that you can double your namespace by creating two maps! :-)

  • Generate sound(voice) from a String

    Hello everybody.
    I would like to generate sound from a String at Symbian devices automaticaly. I wil receive the value of this String remotely and then it will be generated to a sound.
    The String will not be very long (3 to 4 words).
    For example,
    String test="Hello everybody";Is it possible via J2ME API?
    Or do I need any external library?
    Regards,
    kalgik

    You can't easily do it... you can using reflection:
    MyStaticClass.class.getField().getXXX("MyVariable") //depending on what type the field is...But this seems like it may be a flawed design. Maybe you should try making a static HashMap in the class, use a Static init block and static get/set methods:
    public class StaticClass
        static Map properties;
        static
            properties = new HashMap();
            properties.put("MyVariable", "Some Value");
            properties.put("OtherVariable", new Integer(3));
        public static Object get(String property)
            return properties.get(property);
        public static void set(String property, Object value)
            //Maybe some code checking to make sure object is right type
            //or don't use a set method at all to make the properties immutable
            properties.put(property, value);
    }

  • Need help generating variable name for timeout object

    Below is a function I am using to scale an object down and
    then hide it. It works fine on just one object, but if I try to run
    it on multiple objects at the same time, only the last object gets
    scaled down. I believe this is because the timeout list only ever
    has a single item in it, “ShrinkTimeOut”.
    Does each entity in the timeout list need a distinct name?
    And if so, how would I dynamically generate a name and save it so I
    can kill the timeout object once the object has scaled down fully?

    > Does it look like I am getting rid of the timeout object
    properly in my code?
    Now that you mention it, and I have a look, no - it doesn't:
    //not sure of the order of parameters here:
    function fShrinkLoop(mModel, aTimeout) {
    //Creates a variable that contains the vector value of the
    model's
    scale (vector( 1.0000, 1.0000, 1.0000 )).
    nScaleVector = mModel.getPropRef("transform").scale;
    //Checks to see if the model is 1% or less than its original
    size.
    if (nScaleVector[1]<=0.01) {
    //Makes the model invisible.
    mModel.visibility = symbol("none");
    //Kills the timeout object.
    aTimeout.forget();
    } else {
    //If it is not, we scale the model down further and allow
    the loop to
    repeat.
    mModel.scale(0.9);

  • Added dynamic text; How do I stop variable name from showing?

    I am creating a simple game for kids.  On the first page, I added an "input text" field for their first name.  I called the variable firstname.
    When they move to the next page, I used a "dyanamic text" field so I can call them by name on this page.  It works.  However, When I test the game, on the first page, where the firstname is input, it shows    _level0.firstname          instead of just a blank space for them to input their name.
    I know I fixed this in the past and it was something simple, but I can't remember how to do it.  I'd appreciate anyone's help!
    Thanks.

    Beginning with Flash MX (version 6), you assign the text field an instance name using the Property inspector. Although you can use the variable name method with dynamic text fields for backwards compatibility to Flash 5 and earlier versions, Macromedia doesn't recommend this, because you can't control other text field properties, or apply style sheet settings

  • How to know the nos. and variable name from Jframe ?

    Hello Everyone,
    I have just started java programming. I have one form (using jframe) and there are nos. of components like text field, radio buttons, list box, buttons etc.).
    I want to know nos. and type of components (text field, radio buttons, button etc..) and variable name of these components ?
    Is there any way class / method or technique for the same ?
    With Thanks !
    Prashant Shukla

    Since if you are dealing strictly swing here, and no mixed in awt, all you have is JComponents, then where's the problem ... why do you even need to know which JComponent it is?
    This what you have?
    class StuffWithListeners  extends JFrame  implements ActionListener, KeyListener {
      StuffWithListeners() {
        jb = new JButton("GO");
        ta = new JTextArea(10,20);
        jb.addActionListener(this);
        ta.addKeyListener(this);
      public void actionPerformed(ActionEvent ae) {
      public void KeyPressed(KeyEvent ke) {
    }Edited by: abillconsl on Dec 14, 2007 5:23 PM
    null

  • Creating object with names from a String Array

    Hi all,
    This might be a stupid question .. I have the following method:
         public OptionInputPanel(Option newO, String [] parameter){
              super(new BorderLayout());
              o = newO;
              for (int i = 0; i < parameter.length; i++){
                   testB = BorderFactory.createTitledBorder(parameter);
                   JFormattedTextField parameter[i] = new JFormattedTextField(); // problem
    as you can see I would like to name my text fields with the strings that I have in the parameters array so that I can get their values later on. How can I do it?
    Thanks for help
    Stan

                   JFormattedTextField parameter[i] = new JFormattedTextField(); // problemYou are declare an array of size i, and assigning a single JFormattedTextField to it.
         public OptionInputPanel(Option newO, String [] parameter){
              super(new BorderLayout());
              o = newO;
              JFormattedTextField params[ i ] = new JFormattedTextField();
              for (int i = 0; i < parameter.length; i++){
                   testB = BorderFactory.createTitledBorder(parameter[ i ]);
                   param[ i ] = new JFormattedTextField(parameter[ i ]);
    Resources for Beginners
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java. This one has been getting a lot of very positive comments lately.

  • Object/variable name from unknown input

    Hello,
    Suppose that a program reads data from a file and collects name/address/telephone information. The file contains first-time information and updates. For example a portion of the file could be:
    John, 123 Some Ave, 555-1212
    Paul, 234 Another Blvd, 555-1234
    John, 123 Some Ave, 555-9876
    Meaning that John changed his phone number from the first one to the second one.
    I thought of creating a person class so that I'd end up with something like this:
    person John
    - string address = "123 Some Ave"
    - int telephone = 5551212
    but that created all sorts of problems.
    What's the best way to manage a situation like this where you create and update data from a source? I used a file as an example, but it could be user input or whatever.
    I just started learning Java a few days ago, so bear with me ;-)
    Many thanks in advance!

    ironcito wrote:
    1) How to name the object when I create it.
    person whatever_the_file_says = new person();You don't need to. You should be storing you objects in an array or a Collection.
    array[index] = new Person(....); // array
    list.add(new Person(....));  // ArrayList
    2) How to search if an object by that name already exists.You would iterate over your array and compare each object with your new data. If you use a collection then you need to give Person class an equals method and use contains().
    3) Update existing objects.
    whatever_the_file_says.telephone = new_valueYour Person class needs to have the appropriate setter method.

  • Dynamic Variable name (for int/long) from a String variable

    Hi,
    I want to give a int/long variable name from a String.
    for ex.
    String str = lookup + "Id";
    lookup is a String variable coming from XML. Now, for instance lookup="name". So str = "nameId".
    Now I want to create a int/long variable by nameId.
    Could anybody tell me the way how to do. Please don't tell to use MAP.
    Edited by: Shah on Dec 5, 2007 3:26 PM

    Well you can't. Use a Map.
    The compiler translates variable names into slot numbers, either within an object or withing the local "stack frame" and these slot numbers are assigned names at compile time. No new slots can be created at run time. Java is not Basic.
    Reflection allows you to find existing field names and methods (not local variables), so it's possible to map, for example, XML attribute names to field names or setters in an object but the names have to be known at compile time.

  • Substitute a variable name by String ?

    Hi
    is it possible to substitute a variable name by a String ? if yes then please tell me how :-)
    thx
    pain

    You might be able to use the Reflection API to get what you want, but every other time this question's been asked the asker really needed to use a HashMap instead...
    Good Luck
    Lee

  • Problems with Reflection API and intantiating an class from a string value

    I want to instantiate a class with the name from a String. I have used the reflection api so:
    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;
    Let's say my class name is "Frame1".
    and then if i use:
    Frame1 frm = (Frame1) createObject("Frame1");
    everything is ok but i cannot do this because the name "Frame1" is a String variable called "name" and it doesn't work like:
    name frm = (name) createObject("Frame1");
    where i'm i mistaking?
    Thanks very much!

    i have understood what you have told me but here is a little problem
    here is how my test code looks like
    Class[] parameterTypes = new Class[] {String.class};
    Object frm = createObject("Frame1");
    Class cls = frm.getClass();
    cls.getMethod("pack",parameterTypes);
    cls.getMethod("validate",parameterTypes);
    everything works ok till now.
    usually if i would of had instantiated the "Frame1" class standardly the "cls" (or "frm" in the first question ) object would be an java.awt.Window object so now i can't use the function (proprietary):
    frame_pos_size.frame_pos_size(frm,true);
    this function requires as parameters: frame_pos_size(java.awt.Window, boolean)
    because my cls or frm objects are not java.awt.Window i really don't find any solution for my problem. I hope you have understood my problem. Please help. Thanks a lot in advance.

  • Dynamic variable name generation

    Hi people,
    Is there any way of generating variable names dynamically in java in a loop? i.e.
    for(int i = 0; i<arrayLength; i++) {
    ArrayX.add(position, object)
    X++
    Where X is 0,1,2...etc. so i would have Array1 with something in it, Array2 with something in it, Array3 and so on.
    This is just a simple example but I've basically got an initial array of URL objects and then I want to call my getURL method on each link in my inital array and store the links associated to each initial URL in a different Array.
    Hope it makes sense, and i hope someone can help!
    Thanks in advance.

    Your example code is not clear to me (what is "position?"), and your description using URLs doesn't seem to need what you are asking for. I would be careful about using arrays - people sometimes use arrays when classes should be used.
    Anyway, I think you can get close to what you want by using a HashMap. You can use Strings as keys and the Strings would be "array01" "array02" etc.

  • Jsp 2.0 tagfile with name-from-attribute causes jasper exception

    hello there, i'm messing around with jsp 2.0 tag files and can't get this simple example to work (tried it for hours in variations ...)
    the tag file:
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ attribute name="v" required="true" %>
    <%@ variable name-from-attribute="v" variable-class="java.lang.Long" alias="a" scope="AT_END" %>
    <c:set var="a" value="${123}"/>
    <p> TAG: ${v} = ${a} </p>the jsp file:
    <%@ taglib prefix="demo" tagdir="/WEB-INF/tags/demo" %>
    <demo:varAttr v="x"/>
    <p> JSP: x = ${x} </p>exception :
    org.apache.jasper.JasperException: Unable to compile class for JSP
    root cause:
    java.lang.RuntimeException: org.apache.jasper.JasperException: /WEB-INF/tags/demo/varAttr.tag(3,1) The attribute directive (declared in line 2 and whose name attribute is "v", the value of this name-from-attribute attribute) must be of type java.lang.String, is "required" and not a "rtexprvalue".
    ... and so on
    everything else works fine (name-given attribute).
    i use tomcat 5.9.
    any ideas? maybe somebody could try my example on a different installation.
    thank you in advance for any help, because i ran out of ideas.

    The attribute "v" is not allowed to take runtime expressions if you are using it with a name-from-attribute.
    rtexprvalue defaults to true, so you must explicitly make it false.
    <%@ attribute name="v" required="true" rtexprvalue="false" %>Cheers,
    evnafets

  • Generate key or filename basedon strings, regardless of order

    I have a fundamental question that seems like it would have a simple answer, but I'm just not seeing it.
    I need to generate a key from two strings, and the key must be the same regardless of the order of the strings, so long as they are the same strings.
    E.g. consider the following method:
    public static String generateKey(String s1, String s2);This method should return a key based on the two strings passed in. If the strings are in a different order, but are the same, it should generate the same key.
    A simple answer seems like simply using the lexographical order of the strings and appending them. E.g. "foo" and "bar" would always retury "bar-foo" - which is easy enough by simply comparing the strings.
    I'm looking for a more elegant algorithm to generating this string, such as hashes or th e like.
    Any suggestions?
    Thanks.

    [code[
    public static String generateKey(String s1, String s2)
    int h1 = s1.hashCode() ;
    int h2 = s2.hashCode() ;
    return (h1<h2) ? (s1+s2) : (s2 + s1);
    [code[                                                                                                                                                                                                                                                                                                                                       

Maybe you are looking for

  • Does Time Machine save my songs from itunes?

    I am trying to buy a new MacBook but want to make sure everything important is saved from my Old Mac I backed up everything on Time Machine Using an external hardrive I just want to make sure all of my Itunes songs are backed up as well. Can anyone h

  • Purchase Order Table Control

    Hi,   I am trying to change the columns in the table control of the purchase order screen (ME21N) but cant seem to able to do it, To be more detailed I clicked on the "Configuration" button of the table control, clicked on "Administrator" and made th

  • ECC Report showing Outline Agreements WITH related Release Orders

    Does anyone know of a report in ECC which will display all Outline Agreements together with all the Related Release Orders associated with each Agreement Number? I have trawled through hundreds of SAP transaction codes and cannot find something that

  • Syncing two macs: what will work without icloud?

    Hello. I'm considering buying a second mac, or finding a totally different solution. One of the key questions is: can i still sync two macs; or: what, if anything at all, will sync, what won't without using icloud (which is  totally out of the questi

  • Previous sixmonths data

    hi guys,           i am writing customer exits in bex.i need to populate previous six months data.can anybody let me know  the function module name which gives the previous sixth month name?highly appreciated. thansks and regards, nataraj.