+ 2
Java Parameter Help (variable name instead of value)
Is it possible to send a variable name as parameter instead of the variable value? See code for question in comments. https://code.sololearn.com/c7XnpuC04qAo/?ref=app
6 Réponses
+ 3
Hello, did you try java.lang.reflect ?
https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/package-summary.html
I adjusted your code for variable "a", but since you want to send variable name, you should send a String.
I hope my example helps you.
Cheers
enrico
https://code.sololearn.com/c1fLq4qWJPEP/?ref=app
+ 3
Andre Daniel this depends on your application needs.
You can simply ignore the exception:
try {
...
} catch(NoSuchFieldException e){
//ignore
}
or implement something different, like stopping the execution or logging the exception...
+ 2
Enrico Menabeni can you give the example?
My attempts aren't working:
static void set(String var_name) throws Exception {
int num = 0;
//try {
num = Program.class.getDeclaredField(var_name).getInt(null);
num = num * 10; Program.class.getDeclaredField(var_name).set(null, num);
} catch(NoSuchFieldException e) {
System.out.println("Variable "+var_name+" does not exist");
}
Does not work, neither if I cast the try and catch inside the function.
If it's too much work, I understand.
+ 2
Andre Daniel maybe because you commented the try statement?
I updated code with working exception handling.
https://code.sololearn.com/c1fLq4qWJPEP/?ref=app
+ 1
Enrico Menabeni how would you handle the exception if I try to set a variable that does not exist. //like set(d);
0
becouse you are using static variables which belongs to the class, when you use the command new = , you create a new object and this is call a instance variable and so your value could change rather than the static variables that dont change and has only one copy and value for all program and only can use in a static context