Er Utkarsh Bajpai posted: "Friends, here i am going to tell u a trick to overwrite a value in final variable in java.
As, Till our previous knowledge of Java, we know that final variable are those variable which remain constant during the runtime of the program or you can say that"
Respond to this post by replying above this line |
New post on Encapsulate {Ideas}
|
|
Friends, here i am going to tell u a trick to overwrite a value in final variable in java.
As, Till our previous knowledge of Java, we know that final variable are those variable which remain constant during the runtime of the program or you can say that "final variables are nothing but constants. We cannot change the value of a final variable once it is initialized."
But today i am going to change the value of the final (Constant) variable in java.
I am going to use the classes of Reflection in java.
Below are the steps to overwrite the variable in java
- Create a class, for moment say Demo_final ( e.g class Demo_final)
- Then declare a final variable with no value ( e.g Final int var; )
- now initialize it with a value int the constructor as we know that uninitialized final variable can only be initialized in the constructor, anonymous block or in static blocks
for example :
Demo_final()
{
var=100;
}
- now in the main function create the object of this class
Demo_final df=new Demo_final();
- Now using the Field class (present in "import java.lang.reflect.Field;" package )
A field is a class, interface, or enum with an associated value. Methods in the java.lang.reflect.Field class can retrieve information about the field, such as its name, type, modifiers, and annotations. (The section Examining Class Modifiers and Types in the Classes lesson describes how to retrieve annotations.) There are also methods which enable dynamic access and modification of the value of the field. These tasks are covered in the following sections:
- now make this field accessible by writing
f.setAccessible(true);
now set a new valyue to final variable var by writing the code "f.set(pf,10 );"
Now below is the full code :
Read more of this post
Er Utkarsh Bajpai | November 2, 2015 at 6:43 am | Tags: Field, final, getClass(), override, overwrite, reflection, trick, variable
| Categories: JAVA, JAVA BASIC, JAVA Discussion
| URL: http://wp.me/p5JOdg-br
|
|
|
|
|