How to get name of variable passed to method

How can I get the name of the variable that's passed into a method, in the method?
for instance: the following code prints an array to a text file, and includes the name of the array in the name of hte text file. So, to call it, I have to do this:
printarray(myArray, "myArray")
so that the text "myArray" gets passed in & used in teh fileNM output.
This is inelegant, and I'd like to just call it like this:
printarray(myArray)
and have the method extract that name.
void printarray(String printstuff[], String arrayname) throws Exception
    String fileNM = "arrayprint_" + arrayname +".txt";
    FileWriter printme = new FileWriter(fileNM);
    String newline = System.getProperty("line.separator");
        String tab = "\t";
    for (int i = 0; i<printstuff.length; i++)
        printme.write(i + tab + printstuff[i]  + newline);
    printme.close();
    } // end printarray

Let me try to put this in different words and see if I convince you...
I think you are getting confused between variable names that you use refer a variable within your class and "names" that you associate with a variable based on the data it holds.... In your example
String[] myArray;here 'myArray' is the name of the reference to the variable printstuff[]. When you call the method
printarray(myArray) a copy of this reference is passed to that method.
But you also want to pass another variable that represents the description of the array (which you are referring to as the name). In this case one of the ways of doing this what you had pointed out which is
printarray(myArray, "myArray");If you don't like this and think its inefficient you should do a bit of reading on the basics of what a variable is, what a reference to a variable etc. Alternativel you can define your own class that convinces you like
public class MyArray
      private String[] myArray;
      private String myArrayName;
      public MyArray(String myArrayName, String[] myArray)
                  this.myArrayName=  myArrayName;
                  this.myArray = myArray;
      public String[] getArray()
                return myArray;
      public String getName()
                  return myArrayName;
}Edited by: deepak_1your.com on 17-Apr-2008 14:12

Similar Messages

  • How to get system Environment variable?

    How to get system Environment variable without using jni?
    just like "JAVA_HOME" or "PATH"...
    Any reply is help to me!! :-)

    Thx for your reply...
    I get it!!!
    Read environment variables from an application
    Start the JVM with the "-D" switch to pass properties to the application and read them with the System.getProperty() method. SET myvar=Hello world
    SET myothervar=nothing
    java -Dmyvar="%myvar%" -Dmyothervar="%myothervar%" myClass
    then in myClass String myvar = System.getProperty("myvar");
    String myothervar = System.getProperty("myothervar");
    This is useful when using a JAVA program as a CGI.
    (DOS bat file acting as a CGI) java -DREQUEST_METHOD="%REQUEST_METHOD%"
    -DQUERY_STRING="%QUERY_STRING%"
    javaCGI
    If you don't know in advance, the name of the variable to be passed to the JVM, then there is no 100% Java way to retrieve them.
    NOTE: JDK1.5 provides a way to achieve this, see this HowTo.
    One approach (not the easiest one), is to use a JNI call to fetch the variables, see this HowTo.
    A more low-tech way, is to launch the appropriate call to the operating system and capture the output. The following snippet puts all environment variables in a Properties class and display the value the TEMP variable. import java.io.*;
    import java.util.*;
    public class ReadEnv {
    public static Properties getEnvVars() throws Throwable {
    Process p = null;
    Properties envVars = new Properties();
    Runtime r = Runtime.getRuntime();
    String OS = System.getProperty("os.name").toLowerCase();
    // System.out.println(OS);
    if (OS.indexOf("windows 9") > -1) {
    p = r.exec( "command.com /c set" );
    else if ( (OS.indexOf("nt") > -1)
    || (OS.indexOf("windows 2000") > -1 )
    || (OS.indexOf("windows xp") > -1) ) {
    // thanks to JuanFran for the xp fix!
    p = r.exec( "cmd.exe /c set" );
    else {
    // our last hope, we assume Unix (thanks to H. Ware for the fix)
    p = r.exec( "env" );
    BufferedReader br = new BufferedReader
    ( new InputStreamReader( p.getInputStream() ) );
    String line;
    while( (line = br.readLine()) != null ) {
    int idx = line.indexOf( '=' );
    String key = line.substring( 0, idx );
    String value = line.substring( idx+1 );
    envVars.setProperty( key, value );
    // System.out.println( key + " = " + value );
    return envVars;
    public static void main(String args[]) {
    try {
    Properties p = ReadEnv.getEnvVars();
    System.out.println("the current value of TEMP is : " +
    p.getProperty("TEMP"));
    catch (Throwable e) {
    e.printStackTrace();
    Thanks to W.Rijnders for the W2K fix.
    An update from Van Ly :
    I found that, on Windows 2003 server, the property value for "os.name" is actually "windows 2003." So either that has to be added to the bunch of tests or just relax the comparison strings a bit: else if ( (OS.indexOf("nt") > -1)
    || (OS.indexOf("windows 2000") > -1 )
    || (OS.indexOf("windows 2003") > -1 ) // works but is quite specific to 2003
    || (OS.indexOf("windows xp") > -1) ) {
    else if ( (OS.indexOf("nt") > -1)
    || (OS.indexOf("windows 20") > -1 ) // probably is better since no other OS would return "windows" anyway
    || (OS.indexOf("windows xp") > -1) ) {
    I started with "windows 200" but thought "what the hell" and made it "windows 20" to lengthen its longivity. You could push it further and use "windows 2," I suppose. The only thing to watch out for is to not overlap with "windows 9."
    On Windows, pre-JDK 1.2 JVM has trouble reading the Output stream directly from the SET command, it never returns. Here 2 ways to bypass this behaviour.
    First, instead of calling directly the SET command, we use a BAT file, after the SET command we print a known string. Then, in Java, when we read this known string, we exit from loop. [env.bat]
    @set
    @echo **end
    [java]
    if (OS.indexOf("windows") > -1) {
    p = r.exec( "env.bat" );
    while( (line = br.readLine()) != null ) {
    if (line.indexOf("**end")>-1) break;
    int idx = line.indexOf( '=' );
    String key = line.substring( 0, idx );
    String value = line.substring( idx+1 );
    hash.put( key, value );
    System.out.println( key + " = " + value );
    The other solution is to send the result of the SET command to file and then read the file from Java. ...
    if (OS.indexOf("windows 9") > -1) {
    p = r.exec( "command.com /c set > envvar.txt" );
    else if ( (OS.indexOf("nt") > -1)
    || (OS.indexOf("windows 2000") > -1
    || (OS.indexOf("windows xp") > -1) ) {
    // thanks to JuanFran for the xp fix!
    p = r.exec( "cmd.exe /c set > envvar.txt" );
    // then read back the file
    Properties p = new Properties();
    p.load(new FileInputStream("envvar.txt"));
    Thanks to JP Daviau
    // UNIX
    public Properties getEnvironment() throws java.io.IOException {
    Properties env = new Properties();
    env.load(Runtime.getRuntime().exec("env").getInputStream());
    return env;
    Properties env = getEnvironment();
    String myEnvVar = env.get("MYENV_VAR");
    To read only one variable : // NT version , adaptation for other OS is left as an exercise...
    Process p = Runtime.getRuntime().exec("cmd.exe /c echo %MYVAR%");
    BufferedReader br = new BufferedReader
    ( new InputStreamReader( p.getInputStream() ) );
    String myvar = br.readLine();
    System.out.println(myvar);
    Java's System properties contains some useful informations about the environment, for example, the TEMP and PATH environment variables (on Windows). public class ShowSome {
    public static void main(String args[]){
    System.out.println("TEMP : " + System.getProperty("java.io.tmpdir"));
    System.out.println("PATH : " + System.getProperty("java.library.path"));
    System.out.println("CLASSPATH : " + System.getProperty("java.class.path"));
    System.out.println("SYSTEM DIR : " +
    System.getProperty("user.home")); // ex. c:\windows on Win9x system
    System.out.println("CURRENT DIR: " + System.getProperty("user.dir"));
    Here some tips from H. Ware about the PATH on different OS.
    PATH is not quite the same as library path. In unixes, they are completely different---the libraries typically have their own directories. System.out.println("the current value of PATH is: {" +
    p.getProperty("PATH")+"}");
    System.out.println("LIBPATH: {" +
    System.getProperty("java.library.path")+"}");
    gives the current value of PATH is:
    {/home/hware/bin:/usr/local/bin:/usr/xpg4/bin:/opt/SUNWspro/bin:/usr/ccs/bin:
    /usr/ucb:/bin:/usr/bin:/home/hware/linux-bin:/usr/openwin/bin/:/usr/games/:
    /usr/local/games:/usr/ccs/lib/:/usr/new:/usr/sbin/:/sbin/:/usr/hosts/:
    /usr/openwin/lib:/usr/X11/bin:/usr/bin/X11/:/usr/local/bin/X11:
    /usr/bin/pbmplus:/usr/etc/:/usr/dt/bin/:/usr/lib:/usr/lib/lp/postscript:
    /usr/lib/nis:/usr/share/bin:/usr/share/bin/X11:
    /home/hware/work/cdk/main/cdk/../bin:/home/hware/work/cdk/main/cdk/bin:.}
    LIBPATH:
    {/usr/lib/j2re1.3/lib/i386:/usr/lib/j2re1.3/lib/i386/native_threads:
    /usr/lib/j2re1.3/lib/i386/client:/usr/lib/j2sdk1.3/lib/i386:/usr/lib:/lib}
    on my linux workstation. (java added all those execpt /lib and /usr/lib). But these two lines aren't the same on window either:
    This system is windows nt the current value of PATH is:
    {d:\OrbixWeb3.2\bin;D:\jdk1.3\bin;c:\depot\cdk\main\cdk\bin;c:\depot\
    cdk\main\cdk\..\bin;d:\OrbixWeb3.2\bin;D:\Program
    Files\IBM\GSK\lib;H:\pvcs65\VM\win32\bin;c:\cygnus
    \cygwin-b20\H-i586-cygwin32\bin;d:\cfn\bin;D:\orant\bin;C:\WINNT\system32;C:\WINNT;
    C:\Program Files\Dell\OpenManage\Resolution Assistant\Common\bin;
    d:\Program Files\Symantec\pcAnywhere;
    C:\Program Files\Executive Software\DiskeeperServer\;C:\Program Files\Perforce}
    LIBPATH:
    {D:\jdk1.3\bin;.;C:\WINNT\System32;C:\WINNT;d:\OrbixWeb3.2\bin;D:\jdk1.3\bin;
    c:\depot\cdk\main\cdk\bin;c:\depot\cdk\main\cdk\..\bin;
    d:\OrbixWeb3.2\bin;D:\Program Files\IBM\GSK\lib;
    H:\pvcs65\VM\win32\bin;c:\cygnus\cygwin-b20\H-i586-cygwin32\bin;d:\cfn\bin;
    D:\orant\bin;C:\WINNT\system32;
    C:\WINNT;C:\Program Files\Dell\OpenManage\ResolutionAssistant\Common\bin;
    d:\Program Files\Symantec\pcAnywhere;
    C:\Program Files\Executive Software\DiskeeperServer\;C:\Program Files\Perforce}

  • How to get names of INCLUDE or FORM within included forms

    Hello,
    I want to get names of Include program and included form within included forms.
    I tried SY-REPID or SY-CPROG but these two SYST variables return the name of report program that performs the form, not the name of Include or form.
    Please give me any advice about how to get names of include / included form.
    thanks and regards,
    Hozy

    You can use the statement
    READ REPORT <Report name> into itab
    to read the source code into an internal table.
    Later you can use the "Contains Pattern" operator to get the statements that you need.

  • How to get name of sbRIO programatically

    How to get "name" and "Comment" of sbRIO which I write to sbRIO-9602 in MAX in Identification box (Model, Serial number, MAC address, Name)?
    Solved!
    Go to Solution.

    That shows:
     - IP settings
          - IP adress:        136...etc.
          - DNS name:      MyMaster5                   - THAT IS WHAT I NEED, just in wrong place - in MAX it is not in IP settings, that's why i didn't searched for it there.
          - subnet mask    255.255.255.0
          - gateway          136...
          - DNS server      136...
     - MAC address        00800...
     - serial number        16....
     - system state        Running
     - model name         sbRIO-9602
     - model code          7373
     - password protected restarts?    T/F
     - halt if TCP/IP fails?                   T/F
     - locked?                                   T/F
     - use DHCP?                             T/F
    Still there is no "comment" as in MAX. But that's not so important now.
    I have LW Development system 2009 SP1 Profesional, Realtime Development 2009 SP1
    Thanks very much!

  • How to get name of table from front end

    Hi,
    How to get name of table from front end in EBS 11i?
    thanx
    Ashish

    Hi
    Sandeep is correct. The "Help"/"Record History" will give you the table/view name, but sometimes this particular menu function give me a "Record History is not available here." error message.
    I then use the following menu functions (this will also give you additional information, like column details).
    1) Open Forms
    2) Click on Help/Diagnostics/Examine (*you might have to enter the APPS password at this point)
    3) Change "Block" to "System"
    4) Change "Field" to "Last_query"
    The system will populate the "Value" field with the query that was executed in order to populate the form.
    Regards
    Frank

  • How to get BW-BPS variable value into Visual Basic?

    Hello,
    Scenario:
    Time characteristic 0FISCYEAR has a variable ZVFYEAR. In layout this time characteristic is defined as DATA COLUMN. When user changes VFYEAR variable’s value i want to get the value of variable into Visual Basic and to format header for table in the layout.
    How to get BW-BPS variable value into Visual Basic?
    Could you help me?
    Thanks in advance.
    Best Regards,
    Arunas Stonys

    Hi,
    If i understand your requirments correctly ,you need to read the value of the Variable and Put it on the layout. Here is how  i would solve this,
    Read the value of the variable using an ABAP program.The logic for this would be to read the variable value and post it on the layout on a cell.You can do this by calling the ABAP program on opening the layout.this can be done using LB_EXIT_FM  T-code. Now using the  SAP delivered SAPAfterDataPut  macro, read the cell in which you have placed the variable values and assign it to the necessary values you want to on the layout.All this will be done before the layout opens.
    Hope this helps.
    regards
    Sai Vishnubhatla

  • How to get names of sub tabs?

    Hi All,
    Could someone tell me how to get names of all sub tabs?
    I have Parent Tab T1. T1 has 3 sub tabs T1_1, T1_2 and T1_3.
    I would like to have T1_1, T1_2 and T1_3 sub tab names in the list.
    Thanks in advance!!
    Dip

    Dip,
    You can get the tab names from apex dictionary views, apex_application_tabs & apex_application_parent_tabs . Thanks.
    Regards,
    Manish

  • How to get names of method parameters ?

    How to get names of method parameters (Not only their type and value) is it only possible during debugging ??
    for example void myFunction(int a,int b)
    I need the "a" , and the "b" The issiue is about the java.lang.reflect.InvocationHandler ,
    and its method invoke(Object proxy,
    Method method,
    Object[] args)
    throws Throwable
    I Have the parameter objects themself and their types using method.getParameters() , this is fine ,, but i need the names of the parameters !!!

    If the class file was compiled without debug information included then it is impossible to get the original parameter names, as used in the source code.
    However, If the class file does include debug information, then the method names are hidden deep within the class file. You'd need to parse the class file yourself. Check out a copy of the Java VM Specification for a detailed format of the java class file format.
    It's not a trivial task to parse the java class file, and the VM spec isn't easy reading. You'd nearly be writing a class file disassembler.

  • How to get names of all hard disks?

    Hi,
    How to get names of all hard disks.
    For example:
    There are 3 disks in my computer: A, C,D (OS:&#12288;Windows).
    and then I want to know how many disks (3) and their names( A, C, D) are there?
    Please give me some code sapmles. Thanks.
    (---sorry, my English is not very well----)

    Look at a few of these
    http://onesearch.sun.com/search/developers/index.jsp?qt=%22hard+disk%22+label&qp=forum%3A31&qp_name=Java+Programming&col=devforums

  • How to get an environment variable from OS in class ?

    Hello,
    How to get an environment variable from OS in class ?
    Thanks !

    An example of a Java application that does this is Ant, when you add a line like this in your build.xml:
    <!-- Import environment variables -->
    <property environment="env"/>
    I have looked at the source code of Ant 1.3, especially the file src/main/org/apache/tools/ant/taskdefs/Execute.java. Look at the methods getProcEnvironment() and getProcEnvCommand(). Ant uses an OS-dependent trick to get the environment variables.
    You can download the Ant source code from http://jakarta.apache.org/ant
    Jesper

  • How to get the session variable value in JSF

    Hi
    This is Subbus, I'm new for JSF framewrok, i was set the session scope for my LoginBean in faces-config.xml file..
    <managed-bean-name>login</managed-bean-name>
    <managed-bean-class>LoginBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope> like that...
    So all parameter in LoginBean are set in session right ?... for example i used userId is the Parameter...
    Now i need to get the the userId parameter from that session in my another JSP page.. how i get that ?..
    Already i tried
    session.getAtrribute("userId");
    session.getValue("userId");
    but it retrieve only "null" value.. could u please help me.. it's very urgent one..
    By
    Subbus

    Where i use that..is it in jsp or backend bean...
    simply i use the following code in one backend bean and try to get the value from there bean in the front of jsp page...
    in LogoutBean inside
    public String getUserID()
         Object sessionAttribute = null;
         FacesContext facescontext=FacesContext.getCurrentInstance();
         ExternalContext externalcontext=facescontext.getExternalContext();
         Map sessionMap=externalcontext.getSessionMap();
         if(sessionMap != null)
         sessionAttribute = sessionMap.get("userId");
         System.out.println("Session value is...."+(String)sessionAttribute);
         return (String)sessionAttribute;
         return "fail";
    JSP Page
    <jsp:useBean id="logs" scope="session" class="logs.LogoutBean" />
    System.out.println("SS value is ...."+logs.getUserID());
    but again it retrieve only null value.. could u please tell me first how to set the session variable in JSF.. i did faces-config only.. is it correct or not..
    By
    Subbus

  • How to get names of all Windows in a Form Application at runtime

    Dear All,
    I want to get the name of all windows in a form module programatically at run time. How to get it?
    Any help or comments will be highly appreciated.
    Thanks in Advance.
    Best Regards
    Bilal

    Hi Francois Degrelle,
    First of all thanks for the response.
    What if I have no items on a content canvas? In my application, I am using content canvas to hold the Image banner and help text of the current form, having no items at all. I am also using tab canvases to hold all items of form. The tabs are displayed on the content canvas at run time. So the tab canvases acts like frames (In my case).
    Now if I am looping through items, it gives me the list of all of the tab canvases. Whereas the tab canvas always has no window assigned, as it is displayed on content canvas which has that Window which I need. Thus I am unable to get the names of windows in my case through the above stated procedure.
    Another option could be if I can get the name of the content canvas upon which the given tab canvas is displayed?
    Any way to do this or some other way to achieve the use case?
    Any help will be highly appreciated.
    Thanks in advance
    Bilal

  • How to get essbase substitution variable in ODI

    Hi All,
    I have a problem that I need to get the substitution variable from Essbase /EAS to work on some SQL statement in ODI.
    How can I do in ODI ???
    Thanks for all ..
    Thomas

    Hi,
    If you read my blog post :- http://john-goodwin.blogspot.com/2009/11/odi-series-planning-11113-enhancements.html
    In the post there is a section on retrieving essbase substitution variables and using them in ODI.
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • How to get name of an entry?

    I search in my schema with code below:
    List<OrganizationPojo> organizationPojoList = new ArrayList<OrganizationPojo>();
         DirContext ctx = null;
         try { 
         // get a handle to an Initial DirContext
         ctx = new InitialDirContext(env);
         String[] attrIDs = { "dc", "objectClass","ou" };
         SearchControls ctls = new SearchControls();
         ctls.setReturningAttributes(attrIDs);
         ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
         String filter = "(&(dc=*) (objectClass=organizationalUnit) (ou=*))";
         NamingEnumeration answer = ctx.search(searchBaseDn, filter, ctls);
         try
                   while (answer.hasMore())
                             SearchResult sr = (SearchResult) answer.next();
                             LdapName dn = new LdapName((String)sr.getNameInNamespace());
                             LdapName rdn = new LdapName((String)sr.getName());
    I learned SearchResult.getName returns the name "relative to search base"
    But i only want to get the name of entry.
    I am getting dn correctly but can not find out how to get rdn relative to parent in the tree.

    More generally, to get the RDN of any search result, you're nearly there:
    List<Rdn> rdns = new LdapName(sr.geNameInNamespace()).getRdns();
    Rdn rdn = rdns.get(rdns.size()-1);

  • How to get name or unix id of last switched System Events process?

    Hello
    I am writing a script to be used as an idle function to send a command to a process as soon as it's not frontmost anymore. So far, I can figure how to get the unix id or name of the frontmost process, but not of the previous process . Here is what I have:
    on idle {}
    my handleProcesses()
    return 5 --- '5' tells idle () to run every 5 seconds.
    end idle
    on handleProcesses()
    tell application "System Events"
    set FrontApp to (get name of every process whose frontmost is true)
    set PrevApp to (get name of previous process)
    end tell
    --- my command here, like tell PrevApp to hide...
    end handleProcesses
    My problem is that "previous process" is not in the System Events dictionary. I cannot use "frontmost if false" either, because this would return all other opened applications, not just the previous one.
    I know one partial solution would be to use Command-Tab, get the name of frontmost, and use Command-tab again. But, it's not really pratical nor elegant.
    What I need is a function which can get my frontmost process name (which is easy), and return it when the process is inactive (no more frontmost).
    Thanks.
    Vic

    You can do what you want if you maintain a record yourself of what used to be frontmost:
    tell application "System Events"
    set FrontApp to (get name of every process whose frontmost is true)
    set lastFrontApp to FrontApp
    repeat while FrontApp = lastFrontApp
    set FrontApp to (get name of every process whose frontmost is true)
    end repeat
    set BackApps to (get name of every process whose frontmost is not true)
    if lastFrontApp is in BackApps then
    --the app is open in the background
    else
    --the app was closed
    end if
    end tell

Maybe you are looking for

  • Splitting the goods receipt qty at the time of COR6N

    Hello Friends, Actually we want to do auto goods receipt at  the time of confirmation (cor6n).I have given the PI03 control key to the operation and phase.So system shows the goods receipt item in goods  movement screen in COR6N. We manage all the ma

  • How can I tell what "generation" i pod touch?

    How can I tell what "generation" ipod touch I have so I can purchase the right case. Thanks!

  • Verizon DSL with DHCP and PPPoE

    Hello, I recently signed up for Verizon DSL (with a Westell 6100 modem) and I am connecting to it through a graphite Airport base station. It was initially set to use DHCP in the TCP/IP section. It would connect to the internet properly but after I s

  • Font Rendering

    Hey, I'm a recent convert from a PC with Windows Vista to a MacBook Pro with OS X and the only thing that I have a problem with is the font rendering, that the fonts seem a lot smaller than on the PC and using Pages or Scrivener, I have to have it up

  • Reinstalling from disc

    I purchased Adobe Creative Suite 6 before the Cloud. I am getting a new computer. Will I still be able to install it again for a second time? I don't want to subscribe as I have paid for the license. Thanks