java - Can i get value of local variable dynamically from array of local variable name -


can value of local variable array of it's name iterating array.below code sample same.

public class testlocalvar { public static void main(string[] args) {     string[] arrlocalvar = {"vara", "varb", "varc", "vard"};             string vara = "i a";     string varb = "i b";     string varc = "";     string vard = "";                for(string localvarname : arrlocalvar){         system.out.println("localvarvalue -->"+localvarname);         //here can value of local variable?      }            system.out.println("## loop end ##");     //printing values out side of loop     system.out.println("vara :"+vara+" ,varb :"+varb+ ", varc :"+varc+ " ,vard :"+vard);         }} 

this doing validating local variables dynamically iterating it's string type name array.

thanks in advance.

local variables not accessible through reflection. have access classes, class members (properties or methods), not local variables used in methods or functions (static methods).

if want validate fields member of class, can access them. following code demonstrate how can values of class instance fields through names.

public class foo {    int a;    string b;     public foo(int a, string b) {        this.a = a;        this.b = b;    }     public static void main(string[] args) {        foo foo = new foo(42, "hello there");         try {            class<?> c = foo.getclass();            // object represent field "a" in class foo            field = c.getdeclaredfield("a");            field b = c.getdeclaredfield("b");             system.out.println(string.format(                    "foo a=%d, b=%s",                     a.getint(foo), // value of field "a" instance foo                    b.get(foo)));        }         catch (nosuchfieldexception | securityexception | illegalargumentexception | illegalaccessexception e) {            e.printstacktrace();        }    } } 

prints:

foo a=42, b=hello there


Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -