This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
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 Elasticsearch in Action this week in the Big Data 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: 1281

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: 41096
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: 4517

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: 19908

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: 1281

Prabhakar Reddy Bokka
Ranch Hand

Joined: Jul 26, 2005
Posts: 193

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:

I agree. Here's the link:
subject: Access Private Variables outside the class?