+ 23

How to forcefully access private variable from outside its class without ordinary getter and setter?

feel free to explain it using demo/sample any programming language, even from assembly programming language point of view.

15th Oct 2017, 5:13 AM
Adi Pratama, S.Kom.
Adi Pratama, S.Kom. - avatar
5 Answers
+ 7
short answer is you don't. well the whole idea of access rights is that the programmer knows what he is doing and by making something private it is simply not intended to be used outside the class. So it makes no sense to "forcefully" get the variable when you could make it protected or public. never the less here is at least something in java: http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html
14th Oct 2017, 9:11 PM
Chrizzhigh - avatar
+ 6
The only reason you might want to do this is for unit tests. In C++ you can write #define private public // import all the header files you want to force open #undefine private You basically tell the compiler to treat the word private differently. Similarly you can use reflection in other languages. A cleaner way would be to give your test classes access in the first place, for example by making them friends of the tested class. The course explains how to befriend classes.
15th Oct 2017, 6:39 AM
1of3 - avatar
+ 5
first question; Why do you want to do that? the purpose of private variables is that they remain private, getters and setters are already violating the concept of data encapsulation, but they are acceptable to a certain degree Second: What do you mean with access, do you want to see the value? Or manipulate it? Print it? Third: there are certain ways to do that depending on the language you're using, but which one are you using?
14th Oct 2017, 9:17 PM
‎ɐısıօլɐ - avatar
+ 4
Check out singleton design pattern. At some point you'll read about the weakness in the pattern and how reflection works in multiple languages.
15th Oct 2017, 8:17 AM
Dark Angel
Dark Angel - avatar
+ 3
why do I fell that you are doing something sneaky?
27th Aug 2018, 11:47 PM
ShadowWrath72 - avatar