Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of a private static field from a class?

Tags:

c#

reflection

Is there any way to get value of private static field from known class using reflection?

like image 539
chief7 Avatar asked Mar 10 '09 02:03

chief7


People also ask

How do you access a private static variable?

A variable declared private static could easily be accessed, but only from the inside of the class in which it is defined and declared. It is because the variable is declared private, and private variables are not accessible outside the class. Within the class, they can be accessed using ClassName. Variable_name .

Can static fields be private?

Just like an instance variables can be private or public, static variables can also be private or public.

How can you access private static member of a class in C++?

It can be accessed by any member function of the class. Normally, it is accessed with the class scope operator. If it is private, use a static member function to read or write it. A static member function: • Is like an ordinary non-member function, but its scope is the class.

How do you set a private static field value in Java?

So: field. set(null, p_fieldValue); This will let you set the static field.


2 Answers

Yes.

Type type = typeof(TheClass); FieldInfo info = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Static); object value = info.GetValue(null); 

This is for a field. For a property, change type.GetField to type.GetProperty. You can also access private methods in a similar fashion.

like image 131
configurator Avatar answered Sep 21 '22 15:09

configurator


I suppose someone should ask whether this is a good idea or not? It creates a dependency on the private implementation of this static class. Private implementation is subject to change without any notice given to people using Reflection to access the private implementation.

If the two classes are meant to work together, consider making the field internal and adding the assembly of the cooperating class in an [assembly:InternalsVisibleTo] attribute.

like image 39
John Saunders Avatar answered Sep 18 '22 15:09

John Saunders