Forums Register Login

Access Private Variables outside the class?

+Pie Number of slices to send: Send
I heard that one can use private variables outside the class...Anyone knows how to do it?

Thanks

Kaustubh
+Pie Number of slices to send: Send
You have been told incorrectly, I believe.
You can provide getXXX() methods, however.
+Pie Number of slices to send: Send
Never...
+Pie Number of slices to send: Send
The short answer is "no". The full answer is a little more complicated...in certain circumstances you can do it using reflection.

See http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html for an example.
+Pie Number of slices to send: Send
Without reflection it's not possible from outside the outer most class. Private members of a nested class are visible in its enclosing class. For example:
+Pie Number of slices to send: Send
Why? Why are you in such a predicament ? If you need to access a private variable outside the class, you have to think about your class design.

Having that said, you can use Spring to do this.
+Pie Number of slices to send: Send
+Pie Number of slices to send: Send
When you need to provide junit test cases for your classes this is mostly used.
There will be many classes which hold business logic in private methods, and private constructors.
Testing those business functionality can not be done with out accessing them in your Test class.

Yes. We can use reflection API for accessing private members of the class in our test classes.
+Pie Number of slices to send: Send
I faced the same problem some time in the past. here's what helped me: http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html
Are we home yet? Wait, did we forget the tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 16494 times.
Similar Threads
What is encapsulation?
Question 80 from Java rules round up
package problem
Class Locks for Static methods
Field Access VS getter/setter-Access
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 07:02:34.