Java variable name is in a string

hi,
I have a class Formatlayout.
Now i created the object:
Formatlayout row = new Formatlayout();
Then I want to set the value of variable in the object row.
I could do this by row.variable="x";
But the name of the variable that I want to set is Stored in a String.
So it should be row.(name in the string)="x";
How can I do this in correct Java code?

Google for "reflection". You will have to use the Field class in the reflection package, and no, I am not going to post a full example. Google for one, try it out, and if it doesn't work, came back, post your code (using code tags), and tell us the exact error message you are getting, or the exact difference between the effect you are seeing and the effect you want to see.

Similar Messages

  • Putting quote round a variable name to make a string

    Hi,
    Hopefully this is a fairly simple task.
    I would like to take a variable name, say Hyp, from my main program and call it in a class, captured in a variable called A and create a string with double quotes surrounding it... to give an answer of "Hyp" which can be used in my program for a further class call which needs the name in quotes.
    I've tried using
    String concat = """+A+""" but this results in an invalid AssignmentOperator
    If I use
    String concat = ""+A+"" I get Hyp with out the quotes - not what is required
    If I use
    String concat = "'"+A+"'" I get 'Hyp' which does not work with the further class which requires "Hyp"
    Can anyone help?

    Escape it with a \ like this:
    String concat = "\""+A+"\"";

  • Access java variable by string name

    Is there a way in java to set a variable by a string name like the $$ option in php?
    What I'm trying to do is set a global String variable from within a loop of key-value pairs. I want to be able to set each variable dynamically without knowing the variable name.
    Instead of doing this:
    this.myVar = newValue;
    I want to do something like:
    this.{"variableName"} = newValue;
    where the string inside the {""} is unknown and comes from data within the loop and one iteration may be "myVar".

    jhowley wrote:
    Well, I kind of thought that wasn't possible and a Map was my backup plan anyway. Thanks for the info.its totally possible with Reflection (but you should use a Map).
    read: [getField(String)|http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getField(java.lang.String)]
    import java.lang.reflect.*;
    public class ReflectionDemo{
    public static void main(String[] args){
         new ReflectionDemo().start();
    public void start(){
         try{
         Class c = this.getClass();
         Field f = c.getDeclaredField("myField");
         int i = f.getInt(this);
         System.out.println(i);
         } catch(Exception e){
         e.printStackTrace();
         int myField = 11;
    }

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

  • Variable name to string

    Hi, I'm really new to TestStand, so this is probably an easy question:
    I'm using TestStand 4.5 and I'm trying to convert the name of a variable, Locals.MaxArrayIndex, which is a numeric variable, into a String, Locals.VarString.
    I know that the Str() function can be used to convert a numeric into a String, but how can I store the actual words "Locals.MaxArrayIndex" in a string?
    Thanks! 

    Hmmm...it works great for Parameters that are arrays, but for me it won't work if the Parameter is a numeric variable. Maybe I'm making a mistake somewhere else that I'm not picking up; so I attached the sequence file if you want to take a look at it.
    The issue arises in the 'Else' statement. I'm pretty sure the syntax in my function and popup are correct, but the String (ParamName) that is supposed to hold the value of the Parameter variable name (DataSelect) doesn't seem to ever be filled and outputted in the error message.
    I would really appreciate it if any of you guys could have a look at the file (I'm sure I'm making some kind of really rookie mistake)
    Thanks! 
    Attachments:
    GenerateError.seq ‏9 KB

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

  • Obtain string of IN variable name in PL/SQL

    Hi,
    Odd question. Is there a way to access an IN variable's object name in a procedure?
    eg.
    procedure (var1    IN VARCHAR2(6),
                    var2    IN VARCHAR2(6),
                    var3    IN VARCHAR2(6))
    IS....You run this procedure and pass in parameters of:
    var1 => 'abcdef',
    var2 => 'defghi',
    var3 => 'ghikjl';
    In the code, I want to access the number in the string of the +variable name: var1+
    In a naive sense,
    num_of_in_var := substr(var1, 4,1) would be what i was hoping to achieve, but,
    var1 is set to 'abcdef' so,
    num_of_in_var := substr(var1, 4,1) would return 'd'.
    Any thoughts?
    Thanks
    Edited by: chris001 on Nov 20, 2012 1:16 PM

    Here's an example of how (what you want to do using a procedure or function), can be done using a ADT/UDT (Advance/User Defined Type) in Oracle.
    This approach will not work for standard procedures and functions as this type of dynamic referencing of the code unit/object to itself, is not possible.
    SQL> create or replace type TSomeObject as object(
      2          name    varchar2(10),
      3          id      integer,
      4          day     date,
      5 
      6          member function PropertyByNumber( n integer ) return varchar2
      7  );
      8  /
    Type created.
    SQL>
    SQL> create or replace type body TSomeObject as
      2 
      3          member function PropertyByNumber( n integer ) return varchar2 is
      4                  PLSQL_PROP_GET  constant varchar2(1000) :=
      5                          'declare
      6                                  obj     TSomeObject;
      7                          begin
      8                                  obj := :1;
      9                                  :2 := to_char( obj.#PROPERTY# );
    10                          end;';
    11 
    12                  type            TStrings is table of varchar2(30);
    13                  property        TStrings;
    14                  dynamicBlock    varchar2(1000);
    15                  res             varchar2(4000);
    16          begin
    17                  select
    18                          a.attr_name bulk collect into property
    19                  from    user_type_attrs a
    20                  where   a.type_name = 'TSOMEOBJECT'
    21                  order by
    22                          a.attr_no;
    23 
    24                  dynamicBlock := replace( PLSQL_PROP_GET, '#PROPERTY#', property(n) );
    25                  execute immediate dynamicBlock
    26                  using   in self,
    27                          out res;
    28 
    29                  return( res );
    30          end;
    31 
    32  end;
    33  /
    Type body created.
    SQL>
    SQL> declare
      2          obj     TSomeObject;
      3  begin
      4          obj := new TSomeObject( 'John Doe', 123, trunc(sysdate) );
      5 
      6          for i in 1..3 loop
      7                  dbms_output.put_line( 'property '||i||'='||obj.PropertyByNumber(i) );
      8          end loop;
      9  end;
    10  /
    property 1=John Doe
    property 2=123
    property 3=2012/11/23 00:00:00
    PL/SQL procedure successfully completed.
    SQL> Simplistic example (the PropertyByNumber could be a static class method defined in the abstract parent class) - and one that requires the object to essentially duplicate itself via a bind variable call to dynamic code. Not really the best of approaches, but demonstrates the flexibility (to do even interestingly weird stuff) in PL/SQL.

  • Javascript variable names in strings

    This should be easy, but i can't find any info on how to do
    it!
    It's easy to put the contents of a variable into a string but
    how does one place the name of a Javascript variable into a
    string??
    The only solution i have found is to store the name
    separately as a string, but this isn't very neat.

    OK, simple statement first:
    Integer does not equal string.
    You also seem to be tossing around "runtime" and "static" somewhat liberally. Once you wire an integer (be it a control or block diagram constant) to the case structure's selector, the cases can only take on integer values. This is by design. If you wire a string, the case items take on string values. If you wire an enum, the case items take on the enumeration values. Once you've defined a case structure's cases you can't change them at "runtime". This, by definition, is different code.
    That said, it seems to me that you're looking for an enum.

  • 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

  • How to build a connection string if "Only variable names (i.e.: $variable) may be used as the target of an assignment statement."

    im looping through databases on a server & building  a connection string to each database.
    $SQLConn.ConnectionString = "Server=$SrvName; Database=$DBName; User ID =DBLogin; Password=myPassword;"
    The problem is i get this error:
    Only variable names (i.e.: $variable) may be used as the target of an assignment statement
    I can put the code into an Inlinescript, but then I lose the ability to perform paralellism. Is there any way to construct the connection string in PS Workflow without using an Inlinescript?

    Hi Winston,
    Why not just wrap the InlineScript blocks in a Parallel block, to cause them to execute in parallel?
    For example:
    workflow foo {
    parallel {
    inlinescript {
    start-sleep -Seconds (Get-Random -Minimum 1 -maximum 5)
    "a"
    inlinescript {
    start-sleep -Seconds (Get-Random -Minimum 1 -maximum 5)
    "b"
    Sometimes outputs "a b" and sometimes outputs "b a"

  • Concatinating Strings into Variable Names

    Hi
    I'm not sure if this is even possible but here goes.
    Is there anyway of concatinating (sp? Join together!) two strings and then use the new string as a variable name.
    The reason I ask is that, depending upon what character I read into my program I will want to modify an array of data associated with that character.
    For example if the character read in was @ I would want to modify the array data@. So my question is, is it possible to read in a character such as @, join it with the string "data" and then use the resulting string as a variable name?
    Apologies if this has a simple solution but I'm struggling to come up with it by myself.
    Many thanks.

    Hey
    Thanks for the advice. The problem is that I'm storing the arrays in a hash map already. This is because each character has more than one piece of data associated with it , and as far as I can tell each key entry in a hash table has one and only one piece of data associated with it. But if there is a way of storing multiple pieces of information with a particular key, then that could be a possible solution....
    Any suggestions?

  • Accessing variable names using String

    I have to check up to 13 JCheckBox variables to see if they are checked or not, and I have the variables named: count1, count2, count3,...,count13. I wanted to know if there was a way to go through them in a while loop until I found the last one that was checked. I want to do the following:
    int i = 1;
    while([count+i].isSelected()) {
    i++;
    int foodCount = i;
    //foodCount is stored in database
    I am doing this for a pet store and I don't want to have 12 extra columns in the database - I just want to have one for the overall food count. Any ideas how I can dynamically create a variable name?

    Put the JCheckBoxes in an arrayJCheckBox[] myCheckBoxes = {check1, check2, check3,...,check13};
    JCheckBox someCheckBox = null;
    for (int x=0; x<myCheckBoxes.length; x++) {
      if (myCheckBoxes[x].isSelected()) someCheckBox = myCheckBox[x];
    }

  • Assign j_user value to a java variable in umLogonPage.jsp

    Hi All
    I need to do some post processing immediately after login and require the user id for the same. So how do we acess the value in the user id field and assign it to a java variable in the umLogonPage.jsp..??
    Java specific forums claim that this is not possible directly and can be only done on submit function or through hidden fields in the form. Any ideas with regard to the form that is present in umLogonPage.jsp..??
    Thanks
    Deepak

    Hi,
    we use this for saving the login time of the user. There are few therads about creating a custom login module (for example: [Custom Login Module - how to go on |http://forums.sdn.sap.com/thread.jspa?threadID=357616]).
    We have created a login module which extends AbstractLoginModule, in login() method :
    public boolean login() throws LoginException  {
    Object option = g_sharedState.get("javax.security.auth.login.name");
    if (option != null && !option.equals(""))  {
      String l_userID = (String)option;
      IUserAccount l_account = UMFactory.getUserAccountFactory().getUserAccountByLogonId(l_userID);
      IUserAccount mutableAccount = accountFactory.getMutableUserAccount(account.getUniqueID());     
      l_mutAccount.setLastSuccessfulLogonDate(new Date());
      l_mutAccount.commit();
    about login modules and login stacks start here: [http://help.sap.com/saphelp_nw04/helpdata/en/8c/f03541c6afd92be10000000a1550b0/frameset.htm|http://help.sap.com/saphelp_nw04/helpdata/en/8c/f03541c6afd92be10000000a1550b0/frameset.htm]
    Hope this helps,
    Romano

  • How do I create a variable name on the fly?

    Hi,
    If I have a String containing a value, how do I create a variable name using that value during program execution? That is if I have
    String fred = "newvar";
    How do I then create a new String with the name "newvar" (using the contents of fred)? I will never know what the content of fred is until this point. What I'd like to be able to do is something like
    String fred.subString(0) = "a new value";
    Obviously this won't work but if it did the statement would evaluate to something like
    String newvar = "a new value";
    Appreciate any help you can give,
    Dave.

    Here u go:
       private JCheckBox AddCheckBox( String strText, int nTextID )
          JCheckBox checkbox = null;
          Class checkboxDefinition;
          Class[] stringArgsClass = new Class[] {String.class};
          Constructor stringArgsConstructor;
          Object[] stringArgs = null;
          String arg = "";
          arg = "CheckBox" + nTextID;
          String label = new String(arg);
          stringArgs = new Object[] {label};
          try
            checkboxDefinition = Class.forName("javax.swing.JCheckBox");
            stringArgsConstructor = checkboxDefinition.getConstructor(stringArgsClass);
            checkbox = (JCheckBox) createObject(stringArgsConstructor, stringArgs);
            checkbox.setName(label);
            checkbox.setText(strText);
            checkbox.setSize(new java.awt.Dimension(CQuestionBase.PAGEWIDTH, 21));
            checkbox.putClientProperty("1",new Integer(nTextID));
            checkbox.setVisible(true);
          catch (ClassNotFoundException e)
            System.out.println(e);
          catch (NoSuchMethodException e)
            System.out.println(e);
          return checkbox;
       }This code was based on an example I found about two years ago. You can use the same methodolgy to create objects of any kind. Again, look at java.lang.Reflect.

  • Using a java variable in jsp-Reports?

    Hello everyone,
    is it possible to use a java variable in the xml-definition of a report? Something like
    <%@ taglib uri="/WEB-INF/lib/reports_tld.jar" prefix="rw" %>
    <% String someSqlStatement="select * from emp"; %>
    <rw:report id="myReport">
    <rw:objects id="myObjects">
    <report DTDVersion="9000010" name="myReport">
    <data>
    <dataSource name="Q_1">
    <select>
    <![CDATA[
    <%= someSQLStatement %>
    ]]>
    </select>
    It won't work that way (as the string is not evaluated and inserted into the definition, but how could it be done? Would be great to modify the report programatically that way? Any ideas?
    TIA,
    Marcel Jantz

    To pass values to Reports, you should use the "parameters" attribute in the <rw:report> tag. In the above case you would have:
    <% String myParameters="p_someSqlStatement=select%20*%20from%20emp"; %>
    <rw:report id="myReport" parameters="<%= myParameters %>">
    <rw:objects id="myObjects">
    <report DTDVersion="9000010" name="myReport">
    <data>
    <dataSource name="Q_1">
    <select>
    <![CDATA[ &p_someSqlStatement ]]>
    </select>
    The body of the <rw:objects> tag isn't evaluated since the Reports Builder needs to be able to open and load the <rw:objects> tag. As the Reports builder doesn't run the .jsp on open, it only parses it, the <rw:objects> tag can't have values that need to be evaluated.

Maybe you are looking for