[New post] Trick to overwrite the value of final variable in Java

11 views
Skip to first unread message

Encapsulate {Ideas}

unread,
Nov 2, 2015, 1:43:28 AM11/2/15
to post.encap...@gmail.com
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}

Trick to overwrite the value of final variable in Java

by Er Utkarsh Bajpai

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

Comment    See all comments    Like

Unsubscribe to no longer receive posts from Encapsulate {Ideas}.
Change your email settings at Manage Subscriptions.

Trouble clicking? Copy and paste this URL into your browser:
https://encapsulateideas.wordpress.com/2015/11/02/trick-to-overwrite-the-value-of-final-variable-in-java/

Thanks for flying with WordPress.com

Reply all
Reply to author
Forward
0 new messages