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

Similar Messages

  • Can JavaScript access JSP variable?

    Could we do this? Or, how could we have JavaScript access JSP variable?
    <%
    String fooBar = request.getParameter(......
    %>
    <script language="JavaScript">
    <!--
    if (fooBar  == ...) {
    -->
    </script>

    To access the variable in Javascript you'll have to
    write it out from the JSP. You'll need to do something
    like:
    <%
    String fooBar = request.getParameter(......
    %>
    <script language="JavaScript">
    <!--
    var fooBar = '<%=encodeQuotes(fooBar)%>';
    if (fooBar  == ...) {
    -->
    </script>You'll need to either make sure fooBar doesn't contain
    any quotes or write a function to replace each ' with
    \'.Thanks!
    That works perfectly, without encodeQuote() method in my current case.
    Thanks again. You ar a saviour.

  • Access session variable in Java Function in JSP

    Hi Experts !!
    I am developing an application using STRUTS MVC...
    Very sorry if u have problem understanding my question, i ll try to improve... and sorry if i can't post codes here
    Basic question is ....
    I want to open a word document on pageLoad of JSP, the word document is not a single document, there is a form in which there is a "name" and "template" whenever user clicks on a button there is one action attached to it which creates a copy of that template in a different folder.. on the next page OnLoad i want to open that particular document. for that i have created a variable and also have set in the session, just want to access it in the below code.
    I have a formbean in which i have a variable, the scope is session, that variable i have put it in session also. but i want to access that variable in a "java function" in JSP so that "onLoad" page that function should work.
    JSP---
    <script type="text/javascript">
    function openDocument() {
    var w = new ActiveXObject("Word.Application");
    var docText;
    var obj;
    var a;
    if (w != null) {
    w.Visible = true;
    obj = w.Documents.Open(I HAVE TO ACCESS THAT VARIABLE HERE);
    </script>
    FORMBEAN----
    public class CreateSOWFormBean extends ActionForm {
    private String workflowName;
    private String comment;
    private String sowTemplate;
    private String sowFileCreated;
    public String getSowFileCreated() {
    return sowFileCreated;
    public void setSowFileCreated(String sowFileCreated) {
    this.sowFileCreated = sowFileCreated;
    sowFileCreated is the variable that i have accessed in session and that value i have to pass in that function in JSP....
    I am aware of something like
    obj = w.Documents.Open(<%'sowFileCreated'%>);
    but i m not sure how to write....
    Plz help.....

    If you're working under a framework like struts you should definitely be using JSTL tags rather than scriptlet code to access variables within the page. With JSTL code <% codes can be almost entirely avoided.
    To transfer a value from a Servlet to a JSP don't use a session variable, use a request attribute. Session variables should only be used when values have to survive from one transaction to another.
    You can write something like:
    obj = w.Documents.open('<c:out value="${openURL}"/>');in the Javascript portion of your JSP.
    Just beware of potential problems with quotes. The coresponding code in the Servlet would be like:
    request.setAttribute("openURL", openUrl);

  • Unknown variable or property name 'ReportFilePath'. Error accessing item 'Runstate.Root.Locals.ReportFilePath'. in TestStand

    Hi all.
    I was using Teststand 4.2 up to last week and upgraded to TS 2013. In 4.2 I was using the following to get the location of the teststand report:
    Runstate.Root.Locals.ReportFilePath
    but with TS 2013 this no longer works.. is the following error:
    Unknown variable or property name 'ReportFilePath'.
    Error accessing item 'Runstate.Root.Locals.ReportFilePath'. in TestStand - Get Property Value (String).vi->
    I've tried the following now with no success:
    RunState.Root.Report.Location
    So my question is how can I get the location (path) of the report file during test programmatically please?
    Please find enclosed a screenshot of the report config:
    Solved!
    Go to Solution.
    Attachments:
    TS_ReportConfig.png ‏42 KB

    Shashidhar,
    Thanks for your help! With your tips, I finally got it to work. For anyone else trying to modify report names based on user input after the sequential process model sets the file name path I will re tell what I did:
    Edit the Ni_RerportGenerator.seq plugin found in C:\Program Files (x86)\National Instruments\TestStand 2014\Components\Models\ModelPlugins\
    You go into this file and add the step higlighted in Blue at that same location. Please see the expression I typed in the expression box. Setting Parameters.ReportOptions.NewFileNameForEachUUTStatus to true forces re-evaluation of the report name at the end of the sequentialmodel.seq.
    Then you add a FileGlobal in the sequenatialmodel.seq. I called my FileGlobal ReportFileName
    Then I added an expression in my test sequence that modified the the new FileGlobal I created:
    Finally I updated the report options (Go to Cofigure>Report Options > Report File Pathname and under File/Directory Options select "Specify Report File Path by Expression" and I entered my expression. It appears that you can disregard the evaluated report file path error (box below) because your pathname won't be generated until run-time.
    This worked well for me hopefully it will for others. 
    Thanks,
    Marco

  • Get a variable by a name string?

    Hi,
    I am currently developing an interpreter.
    This interpreter will be initiated with several pieces of strings mixed
    with unknown number of variables with some order which is unknown previously.
    So the better way is just passing one string which contains the variable
    name strings and return a collection of variables specified by the variable
    names contained in this string.
    Problem is:
    How can I get a local variable from a name string in a method, instead of
    by a name variable?
    Java Reflection can only return fields, but not variables
    Any idea?
    And does JNI could do it?
    Any help appreciated
    Thanks in adv
    dunson

    Interpreter for what?

  • Get a variable by a name string? how

    Hi,
    I am currently developing an interpreter which is of cause a class.
    This interpreter will be initiated with several pieces of strings mixed
    with unknown number of variables with some order which is unknown previously.
    So the better way is just passing one string which contains the variable
    name strings and return a collection of variables specified by the variable
    ames contained in this string.
    Problem is:
    How can I get a variable from a name string, instead of a name
         variable?
         Java Reflection can only return fields, but not variables
         Any idea?
         And how JNI could do perphaps?
    Any help appreciated
    Thanks in adv
    dunson

    As far as i know, the names of local variables, that are only used inside methods, are not preserved in the bytecode. That means you can't grab from them by name, whatever you do. You are able to grab members though, through reflection, but it's not very efficient. I wouldn't recommend it.
    As suggested, I think you need to make special provision for this with a structure like a Hashtable. It's better programming practice, it's more efficient, and you'll find it much easier to program.
    Something like this:
    import java.util.*;
    class Doodad {
      Map stuff = new HashMap();
      Object getValue(String code) {
        return stuff.get(code);
      void setValue(String code, Object value) {
        stuff.put(code, value);

  • "sCode=0xf​fffbc66: Descriptio​n: Unknown variable or property name 'ReportSty​le'. Error accessing item 'ReportSty​le' when trying to optn the ReportOpti​ons in TestStand 4.0.

    I get the error "sCode=0xffffbc66: Description: Unknown variable or property name 'ReportStyle'.  Error accessing item 'ReportStyle'. when trying to load the ReportOptions in TestStand 4.0.
    Has anyone seen this before?  If so how can I get around it as I will need to disable Report Generation for this system.
    Thank you

    Hello,
    I am not 100% sure how I resolved this issue as it was a few years ago.  However, I have attached the TestStandModelReportOptions.ini file that I used - hope this helps you.
    Attachments:
    TestStandModelReportOptions.ini ‏5 KB

  • How to access Websphere variables using java

    Hi
    I want to access Websphere variables using java.
    Any help is appreciated!!
    Thanks
    P

    WebSphere Application Server has a bunch environmental variables such as log locations. These are held at the "server", "node", and "cell" level.
    To access them, you have to get the right context. Something like this, I believe...
    InitialContext initialContext = new InitialContext();
    initialContext.lookup("foo:bar/baz/blah"); //correct context hereGo to the IBM website for WAS and do a search on namespace bindings. That should give you some more information.
    Good luck.

  • Access a variable in the Adobe form for Java Scripting

    Hi,
    I am unable to know how to access the variable in a Adobe form.
    The variable is field of an internal table. My adobe form structure is as follows
    MAIN_PAGE->FORMSET->FirstFORM->EXT.
    in the EXT subform the variable(cust)  exists.
    The cust is in turn an internal table.

    Hello Sreelatha,
    I think we cannot hide a page.  as in, page is the main container.  In a container, we can hide any field using some scripting.  Even though if we hide the field, it is present on page but not visible. 
    but if some logic is there, please let me know.
    Thanks,
    Rakesh.
    Edited by: rakhi966 on Sep 8, 2011 8:54 PM

  • Where I have to give the host string name of oracle server in WSAD?

    hi,
    I setup the oracle in my WSAD.But,Its giving below error.
    [3/16/06 13:25:41:332 SGT] 3e75fec4 WsServer A WSVR0001I: Server server1 open for e-business
    [3/16/06 13:25:42:535 SGT] 68bb7ec6 WebGroup I SRVE0180I: [Sample] [Sample] [Servlet.LOG]: ResultData: init
    [3/16/06 13:25:42:551 SGT] 68bb7ec6 SystemOut O the connection started
    [3/16/06 13:25:42:551 SGT] 68bb7ec6 SystemOut O no connection
    [3/16/06 13:25:43:535 SGT] 68bb7ec6 ConnectionFac I J2CA0122I: Resource reference jdbc/MyDataSource could not be located, so default values of the following are used: [Resource-ref settings]
         res-auth: 1 (APPLICATION)
         res-isolation-level: 0 (TRANSACTION_NONE)
         res-sharing-scope: true (SHAREABLE)
         res-resolution-control: 999 (undefined)
    [Other attributes]
    isCMP1_x: false (not CMP1.x)
    isJMS: false (not JMS)
    [3/16/06 13:25:44:285 SGT] 68bb7ec6 FreePool E J2CA0046E: Method createManagedConnctionWithMCWrapper caught an exception during creation of the ManagedConnection for resource jdbc/MyDataSource, throwing ResourceAllocationException. Original exception: com.ibm.ws.exception.WsException: DSRA8100E: Unable to get a PooledConnection from the DataSource.
         at com.ibm.ws.rsadapter.exceptions.DataStoreAdapterException.<init>(DataStoreAdapterException.java:244)
         at com.ibm.ws.rsadapter.exceptions.Dat
    [3/16/06 13:25:44:426 SGT] 68bb7ec6 SystemErr R      at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPhysicalConnection(OracleConnectionPoolDataSource.java:109)
    [3/16/06 13:25:44:426 SGT] 68bb7ec6 SystemErr R      at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:77)
    [3/16/06 13:25:44:426 SGT] 68bb7ec6 SystemErr R [3/16/06 13:25:44:426 SGT] 68bb7ec6 SystemOut O Error on find the database() : java.sql.SQLException: Listener refused the connection with the following error:
    ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
    The Connection descriptor used by the client was:
    SGGSGPTP31DT197.code1.emi.philips.com:1521:CESS
         at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:59)
    [3/16/06 13:25:44:426 SGT] 68bb7ec6 SystemErr R      at com.ibm.ws.rsadapter.DSConfigurationHelper$1.run(DSConfigurationHelper.java:759)
    [3/16/
    But,I given correct URL.The URL I given is
    jdbc:oracle:thin:@sggsgptp31dt197.code1.emi.philips.com:1521:CESS
    sggsgptp31dt197.code1.emi.philips.com -- this is my host machine.
    I think the problem with host string.
    actually when we are trying to enter into the oracle sql,it asking the username,password and host string.I mentioned the username and password in variables tab.I don't know where I have to mention the host string name.
    Please any one help on this.
    Thank you,
    D.Nagireddy.

    I would say that, since the OP has so little info, there are no policies in use.  It there were then this question would never be asked the way it is being asked.
    I had a client call with a letter from their insurance company; an accountant with malpractice insurance.  THey asked the same question inmuch the same way.  "What computer can you users access?"  The question should be more like
    "Do you have a policy that restricts access to computers and do you audit for compliance?"
    I have had other clients whose insurance asked the question in that way.  It produces a better view of what should be happening and how to show compliance.
    I recommend that companies being asked these questions by their legal departments or insurance companies should contract with a god computer security consultant to assist with answering these very tricky questions.  Of course if it is just you boss's
    curiosity  then you may need to discuss his requirements with him in more depth.
    ¯\_(ツ)_/¯

  • Access custom variable value in web.xml context-param?

    My requirement or need is to access a variable value either in a class in my Model project or a backing bean in my View project. For example, one variable I need to access is an application server I am integrating with - 'testserver' or 'productionserver' - I want to be able to configure this within an external file so that I do not have to re-compile my application to change the variable.
    I was thinking about placing this variable in the web.xml <context-param> section as:
    <context-param>
    <param-name>servername</param-name>
    <param-value>testserver</param-value>
    </context-param>
    I need to access this value within a class (not a servlet) on an Application Module service method, though if needed, I could access it from a backing bean and pass it to the service method (less desirable.) Is this a good approach and how do access this variable from within a Java class including any imports I need to do (code example)?
    Thanks and Happy New Year!
    Hopefully most everyone is out spending time with friends and family versus stuck trying to complete a project like me...

    I found an example from SRDemo that provides what I was looking for:
    String serverhostaddress =
    FacesContext.getCurrentInstance().getExternalContext().getInitParameter("param-name-var-in-webxml");

  • Why can't I access the variables in my threads?

    hello.
    another question about threads..
    ==========================
    I have an inner class that implements Runnable (i.e. a thread) and has a variable in it. I want to be able to access that variable from outside the thread class so that I can set or retrieve the variable.
    here is the code for the program
    class myClass
         public static void main(String[] args)
              myClass c = new myClass();
         myClass()
              Thread t = new Thread(new myThread());
              t.number = 1;
              t.start();
         class myThread implements Runnable
              int number = 0;
              public void run()
         }//end myThread
    }//end myClassthe line
    t.number = 1;
    where I try to set the number variable to 1 gives me an error (in the MyClass constructor)
    This is my error
    AccessThreadVars.java:11: cannot find symbol
    symbol  : variable number
    location: class java.lang.Thread
              t.number = 1;
                        ^
    1 errorif I put a method in myThread, and then try to call that method from myClass (via t.MethodName()) it gives me that same error telling me it can't find it..
    what am I doing wrong? how can I get access my thread's variables and methods??

    1. Type names should start with an uppercase letter
    2. t is defined as a Thread, not as a myThread
    (which, may I insist, should be "MyThread"), so the
    compiler has no means of detecting that "number" is
    an accessible field of the object... which wouldn't be accessible anyway, cause you're trying to get attributes from your Runnable after wrapping it inside a Thread.
    Why don't you do something like :
    MyThread t = new MyThread();
    t.number = 1;
    new Thread(myThread).start();?
    I bet you don't use Thread's own methods anyway...

  • Custom class loader and local class accessing local variable

    I have written my own class loader to solve a specific problem. It
    seemed to work very well, but then I started noticing strange errors in
    the log output. Here is an example. Some of the names are in Norwegian,
    but they are not important to this discussion. JavaNotis.Oppstart is the
    name of my class loader class.
    java.lang.ClassFormatError: JavaNotis/SendMeldingDialog$1 (Illegal
    variable name " val$indeks")
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:431)
    at JavaNotis.Oppstart.findClass(Oppstart.java:193)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
    at JavaNotis.SendMeldingDialog.init(SendMeldingDialog.java:78)
    at JavaNotis.SendMeldingDialog.<init>(SendMeldingDialog.java:54)
    at JavaNotis.Notistavle.sendMelding(Notistavle.java:542)
    at JavaNotis.Notistavle.access$900(Notistavle.java:59)
    at JavaNotis.Notistavle$27.actionPerformed(Notistavle.java:427)
    JavaNotis/SendMeldingDialog$1 is a local class in the method
    JavaNotis.SendMeldingDialog.init, and it's accessing a final local
    variable named indeks. The compiler automatically turns this into a
    variable in the inner class called val$indeks. But look at the error
    message, there is an extra space in front of the variable name.
    This error doesn't occur when I don't use my custom class loader and
    instead load the classes through the default class loader in the JVM.
    Here is my class loading code. Is there something wrong with it?
    Again some Norwegian words, but it should still be understandable I hope.
         protected Class findClass(String name) throws ClassNotFoundException
             byte[] b = loadClassData(name);
             return defineClass(name, b, 0, b.length);
         private byte[] loadClassData(String name) throws ClassNotFoundException
             ByteArrayOutputStream ut = null;
             InputStream inn = null;
             try
                 JarEntry klasse = arkiv.getJarEntry(name.replace('.', '/')
    + ".class");
                 if (klasse == null)
                    throw new ClassNotFoundException("Finner ikke klassen "
    + NOTISKLASSE);
                 inn = arkiv.getInputStream(klasse);
                 ut = new ByteArrayOutputStream(inn.available());
                 byte[] kode = new byte[4096];
                 int antall = inn.read(kode);
                 while (antall > 0)
                     ut.write(kode, 0, antall);
                     antall = inn.read(kode);
                 return ut.toByteArray();
             catch (IOException ioe)
                 throw new RuntimeException(ioe.getMessage());
             finally
                 try
                    if (inn != null)
                       inn.close();
                    if (ut != null)
                       ut.close();
                 catch (IOException ioe)
         }I hope somebody can help. :-)
    Regards,
    Knut St�re

    I'm not quite sure how Java handles local classes defined within a method, but from this example it seems as if the local class isn't loaded until it is actually needed, that is when the method is called, which seems like a good thing to me.
    The parent class is already loaded as you can see. It is the loading of the inner class that fails.
    But maybe there is something I've forgotten in my loading code? I know in the "early days" you had to do a lot more to load a class, but I think all that is taken care of by the superclass of my classloader now. All I have to do is provide the raw data of the class. Isn't it so?

  • 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

  • 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

  • How do I stream music to airport express from my iPhone

    I have installed airport express on my macbook pro and can now play music on my stereo system using itunes from my laptop, but I also ant to steam music from my iphone4 to the stereo as well, I have some radio apps on my iphone four that I would like

  • Error message after trying to install Tiger on a B/W G3

    I've tried several times now to install OS 10.4 Tiger from the black install DVD onto my B/W G3. Every time, it gives me a error message saying there were errors during installation and to restart. I've got 512-640 MB of RAM (I've removed one after m

  • Problems transferring multiple files

    I'm trying to write a program to transfer multiple files from a client to a server, but I'm having trouble getting the server to distinguish between them. I have tried both buffered streams, and straight input/output streams, and in both cases, the s

  • GX740 GPU broken

    Hello everyone, I was hoping that someone here could provide me with some advice or tips I have a MSI GX740 with a Mobility 5870 It is about 3 years old. Never had any big problems with it aside the fact that from time to time it would autoshut down

  • Command buttons best practice

    Hello, I would like to ask how others design their GUI with several command buttons (OK button Boolean). For instance, there is a simple application where the user can start data acquisition by clicking on a button with text "Start monitoring". Inste