Is there a way in which we can access private variables of a class in java without setter and getter methods? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Is there a way in which we can access private variables of a class in java without setter and getter methods?

25th Jan 2018, 1:07 PM
Santosh Teurwadkar
Santosh Teurwadkar - avatar
6 Answers
+ 3
use reflection
25th Jan 2018, 1:38 PM
Code Ninja
Code Ninja - avatar
+ 3
Even we can access the private constructor using reflection, I dont understand why did Java team designed something which is against security.
25th Jan 2018, 6:45 PM
Santosh Teurwadkar
Santosh Teurwadkar - avatar
+ 2
@Jeremy Thanks for the answer but it's not correct.Let other put there comment on it.
25th Jan 2018, 1:26 PM
Santosh Teurwadkar
Santosh Teurwadkar - avatar
+ 2
In order to access private fields, you need to get them from the class's declared fields and then make them accessible:Field.setAccessible(true); .Works for standalone java appilication.
25th Jan 2018, 1:48 PM
Code Ninja
Code Ninja - avatar
+ 1
the whole point of declaring it private is so other classes have no access without getter and setter
25th Jan 2018, 1:27 PM
Jeremy
Jeremy - avatar
0
no
25th Jan 2018, 1:23 PM
Jeremy
Jeremy - avatar