Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the private fields of class and its parent class(es) by reflection?

I have the class B and its parent class A, both in namespace Domain.

  • Class A, has the private field a;
  • Class B, has the private field b;

Then I have a Reflection Util in namespace Reflect. If I use this line

instanceOfB.GetType().GetFields(BindingFlags.NonPublic 
         | BindingFlags.Public | BindingFlags.Instance );

to to find all fields (a & b), I get only b. But when I make a protected or public I find them too.

What do I need to do to find the private fields of the base class too?

like image 296
Ralph Avatar asked May 06 '11 12:05

Ralph


People also ask

How do you access a private field using a reflection?

In order to access a private field using reflection, you need to know the name of the field than by calling getDeclaredFields(String name) you will get a java. lang. reflect. Field instance representing that field.

Can I access the private field of a parent class?

The answer is that the private fields of the superclass are not accessible to the methods of the derived class, exactly as they are not accessible to any other method outside the superclass.

How do you access private fields of a superclass?

To access the private members of the superclass you need to use setter and getter methods and call them using the subclass object.

Can Java reflection API access private fields and methods of a class?

Despite the common belief it is actually possible to access private fields and methods of other classes via Java Reflection. It is not even that difficult. This can be very handy during unit testing.


2 Answers

instanceOfB.GetType().BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance );
like image 45
mfeingold Avatar answered Sep 19 '22 15:09

mfeingold


This is the documented behaviour:

Specify BindingFlags.NonPublic to include non-public fields (that is, private, internal, and protected fields) in the search. Only protected and internal fields on base classes are returned; private fields on base classes are not returned.

If you need to get private fields, you'll need to ask the base type. (Use Type.BaseType to find the base type, and call GetFields on that.)

like image 107
Jon Skeet Avatar answered Sep 22 '22 15:09

Jon Skeet