How to access private inner class with reflection?

U

Ulrich Scholz

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
 
T

Thomas Hawtin

Ulrich said:
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.

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
 
Joined
Jul 5, 2010
Messages
1
Reaction score
0
Hi Ulrich
1. Call getDeclaredClasses() on object of type Class1. The return type is an array of Class objects (Class[]). Lets call it "classes"
2. Find the index in the array for which classes[index] = Class2.
3. Call the classes[index].getDeclaredConstructor(). Note that besides passing the classes of the actual parameters you must mandatory pass the class of the enclosing object, i.e Class1. The returned object will be of type "Constructor".
4. Create the instance of your private inner class by calling the constructor obtained in step 3 (lets call it 'constr'). The constructor is invoked by calling the newInstance method on 'constr'. Note that as the first parameter you must pass the instance of the enclosing object followed by the actual parameters of the constructor.
Hope that helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top