wood burning stoves 2.0*
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 Murach's Java Servlets and JSP this week in the Servlets 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: 1270

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: 37926
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: 4341

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

Joined: Oct 27, 2005
Posts: 19651

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

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: http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html

With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Access Private Variables outside the class?
Similar Threads
Field Access VS getter/setter-Access
What is encapsulation?
Class Locks for Static methods
Question 80 from Java rules round up
package problem