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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Access Private Variables outside the class?" Watch "Access Private Variables outside the class?" New topic
Author

Access Private Variables outside the class?

Kaustubh G Sharma
Ranch Hand

Joined: May 13, 2010
Posts: 1277

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

Thanks

Kaustubh


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

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

Joined: Nov 04, 2009
Posts: 2066

Never...


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

Joined: Apr 06, 2010
Posts: 4420
    
    8

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

Joined: Oct 27, 2005
Posts: 19718
    
  20

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:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ajith Kallambella
Sheriff

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

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.


SCJP 5, SCWCD 5
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


SCJP, SCWCD
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Access Private Variables outside the class?