[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

invoke varible by number

Posted on 2011-04-19
9
Medium Priority
?
304 Views
Last Modified: 2012-05-11

public class AA
{
         public String _1_;
         public String _2_;
         public String _3_;

         /** this is question */
        main()
        {
                    for( int i = 0 ; i< 3 ; i++)
                    {
                                String value = getVariable( "_" + i + "_"); <<<<<<<<<<<< how can I invoke global variable by String??
                     }
               
        }
}

0
Comment
Question by:gamjaradio
9 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 752 total points
ID: 35422706
You can't really. The best you can do is to use a String as the key into a Map in which you store the variable as the value
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 752 total points
ID: 35422724
e.g.
import java.util.*;

public class M {
    static String string1 = "A";

    public static void main(String[] args) {
	Map<String, String> m = new HashMap<String, String>();
	m.put("1", string1);
	System.out.println(m.get("1"));
    }
}

Open in new window

0
 
LVL 12

Assisted Solution

by:enachemc
enachemc earned 252 total points
ID: 35422731
you can do it using reflection, but I'm prety sure this is not the way to do it
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 26

Expert Comment

by:ksivananth
ID: 35422803
you can do it through reflection, check this example

http://www.java2s.com/Code/Java/Language-Basics/ObjectReflectiongetfieldvalue.htm
0
 
LVL 28

Assisted Solution

by:dpearson
dpearson earned 248 total points
ID: 35422825
If you really want to do this try something like:

           public main() throws Exception {            
            for (int i  = 1 ; i <= 3 ; i++) {
                  String name = "_" + i + "_" ;
                  Field field = AA.class.getField(name) ;
                  System.out.println("Value of " + name + " is " + field.get(this)) ;
            }
          }

but you are probably better off storing the values in variables that are easier to access.

Doug
0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 748 total points
ID: 35422867

That is how it works through reflection:

import java.lang.reflect.Field;

public class AA
{
         public String _1_;
         public String _2_;
         public String _3_;

    public AA(){
        _1_ = "ttt";
        _2_ = "aaa";
        _3_ = "bbb";
    }

         /** this is question */
     public static void  main(String [] args)
        {
            AA aa = new AA();

                     try{
                Class cls = aa.getClass();
                         Field fieldlist[]
                                      = cls.getDeclaredFields();


                         
                         
                    for( int i = 0 ; i< 3 ; i++)

                    {
                        System.out.println(fieldlist[i].getName().toString());
                        String s =   fieldlist[i].getName().toString().trim();
                        String s1 =  ("_" + (i+1) + "_").trim();



                        if(s.equals(s1)){
          
                            System.out.println((String)fieldlist[i].get(aa));
                       // }
                        }
                                //String value = getVariable( "_" + i + "_"); <<<<<<<<<<<< how can I invoke global variable by String??
                     }

        }
        catch(Exception ex){
            System.out.println("Error " + ex.toString());
            ex.printStackTrace();

}
}
}

Open in new window

0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 748 total points
ID: 35422873

Thsi is the output of the above code;

_1_
ttt
_2_
aaa
_3_
bbb

Open in new window

0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 748 total points
ID: 35422899

This is a little bit shorter version of the above
(the most difficulty and time consuming part as always was not to forget
to add 1 in (i+1) when doing comparison:

import java.lang.reflect.Field;

public class AA
{
         public String _1_;
         public String _2_;
         public String _3_;

    public AA(){
        _1_ = "ttt";
        _2_ = "aaa";
        _3_ = "bbb";
    }

         /** this is question */
     public static void  main(String [] args)
        {
            AA aa = new AA();

                     try{
                Class cls = aa.getClass();
                         Field fieldlist[]
                                      = cls.getDeclaredFields();


                         
                         
                    for( int i = 0 ; i< 3 ; i++)

                    {
  

                        if(fieldlist[i].getName().equals("_" + (i+1) + "_")){
          
                            System.out.println((String)fieldlist[i].get(aa));
                      
                        }
                                //String value = getVariable( "_" + i + "_"); <<<<<<<<<<<< how can I invoke global variable by String??
                     }

        }
        catch(Exception ex){
            System.out.println("Error " + ex.toString());
            ex.printStackTrace();

}
}
}

Open in new window


Output:

ttt
aaa
bbb

Open in new window

0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 752 total points
ID: 35423035
gamjaradio, what is your actual goal here? In a real program you would never normally use a Map for this purpose, and still less use reflection.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Suggested Courses
Course of the Month19 days, 19 hours left to enroll

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question