• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Access Private Variables outside the class?

 
Kaustubh G Sharma
Ranch Hand
Posts: 1283
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I heard that one can use private variables outside the class...Anyone knows how to do it?

Thanks

Kaustubh
 
Campbell Ritchie
Sheriff
Pie
Posts: 50189
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have been told incorrectly, I believe.
You can provide getXXX() methods, however.
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never...
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20665
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Kaustubh G Sharma
Ranch Hand
Posts: 1283
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Prabhakar Reddy Bokka
Ranch Hand
Posts: 197
Java Oracle Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Garik Ustinov
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic