Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / February 2006

Tip: Looking for answers? Try searching our database.

How to access private inner class with reflection?

Thread view: 
Ulrich Scholz - 21 Feb 2006 18:28 GMT
http://www.onjava.com/pub/a/onjava/2003/11/12/reflection.html?page=2
gives an excellent
introduction on how to use reflection to access private fields of
classes for the purpuse of unit testing.

Now assume that we want to test a class Class1.  Class1 has a private
field v of type Vector<Class2>, where Class2 is a private inner class
of Class1.

How can I access v via reflection?  E.g., I cannot  assign v to a
variable in my unit test class because the type Class2 is not visible.

Thank you,

Uli
Thomas Hawtin - 21 Feb 2006 18:54 GMT
> http://www.onjava.com/pub/a/onjava/2003/11/12/reflection.html?page=2
> gives an excellent
[quoted text clipped - 7 lines]
> How can I access v via reflection?  E.g., I cannot  assign v to a
> variable in my unit test class because the type Class2 is not visible.

You can get the class of any object with Object.getClass. That works
even if the class is an anonymous inner class.

The name of the class will be something like mypackage.Class1$Class2,
but you don't need to know that if you go through instances.

However, I would suggest a better approach is to test the public
behaviour of the objects. If you need to test the behaviour of private
methods, factor out a relevant slice of the object.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.