aspose file tools*
The moose likes Java in General and the fly likes Access Private Variables outside the class? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Access Private Variables outside the class?" Watch "Access Private Variables outside the class?" New topic

Access Private Variables outside the class?

Kaustubh G Sharma
Ranch Hand

Joined: May 13, 2010
Posts: 1268

I heard that one can use private variables outside the class...Anyone knows how to do it?



No Kaustubh No Fun, Know Kaustubh Know Fun..
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 36579
You have been told incorrectly, I believe.
You can provide getXXX() methods, however.
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Matthew Brown

Joined: Apr 06, 2010
Posts: 4244

The short answer is "no". The full answer is a little more certain circumstances you can do it using reflection.

See for an example.
Rob Spoor

Joined: Oct 27, 2005
Posts: 19556

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:

How To Ask Questions How To Answer Questions
Ajith Kallambella

Joined: Mar 17, 2000
Posts: 5782
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.

Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Kaustubh G Sharma
Ranch Hand

Joined: May 13, 2010
Posts: 1268

Prabhakar Reddy Bokka
Ranch Hand

Joined: Jul 26, 2005
Posts: 189

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

Joined: Jun 22, 2009
Posts: 31
I faced the same problem some time in the past. here's what helped me:

It is sorta covered in the JavaRanch Style Guide.
subject: Access Private Variables outside the class?
Similar Threads
Class Locks for Static methods
Question 80 from Java rules round up
Field Access VS getter/setter-Access
package problem
What is encapsulation?