Hello, I would like to know how I can change the value of the following constant (for example) through a method.
private static double PIVA=0.16;
Edit: I expressed myself wrong, sorry. I misused the word "constant", I wanted to refer to that "static" variable. It is defined at the beginning of the class.
Thanks for the answers!
What you have there is not a constant, it's just a static variable. To be a constant, it must be defined with the modifier
final
:Being a constant, its value cannot be changed .
Imagine that the field is in a class with the following definition (keeping it as you declare it in your example).
If you want to change its value, you can do it via reflection. You need to know the name of the field you want to modify and then the rest would be a simple use of reflection, like this:
We will create a method to perform the example:
The output of the program:
However, if it were a true constant , that is, the field is marked as
final
, we would see an exception:The output will be:
Now keep in mind that it wo
Field#setAccessible
n't always work. This is because in some runtime environments, there is a SecurityManager that provides application security. As part of security, it prevents fields from being modified by reflection to prevent attacks. This happens for example when executing an Applet.Response before the headline was changed.
¿Cómo cambiar el valor de una constante?
In
java
to define a constant, usefinal
And if you define it as a constant, there is no point in being able to change its value dynamically.