Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value of private field

Tags:

c#

reflection

Why is the following code not working:

class Program {     static void Main ( string[ ] args )     {         SomeClass s = new SomeClass( );          s.GetType( ).GetField( "id" , System.Reflection.BindingFlags.NonPublic ) // sorry reasently updated to GetField from GetProperty...             .SetValue( s , "new value" );     } }   class SomeClass {     object id;      public object Id      {         get         {             return id;         }     }    } 

I am trying to set the value of a private field.


Here is the exeption I get:

 System.NullReferenceException was unhandled   Message=Object reference not set to an instance of an object.   Source=ConsoleApplication7  StackTrace:         at Program.Main(String[] args) in C:\Users\Antonio\Desktop\ConsoleApplication7\ConsoleApplication7\Program.cs:line 18         at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)         at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)         at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()         at System.Threading.ThreadHelper.ThreadStart_Context(Object state)         at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)         at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)         at System.Threading.ThreadHelper.ThreadStart()   InnerException: 
like image 980
Tono Nam Avatar asked Oct 21 '12 00:10

Tono Nam


People also ask

How do you set a field value?

SetFieldValue(value = 10000.0); The FieldByName method returns the field object that represents the given field (salary_fld, in this example), and the SetFieldValue methods uses that field object to set the value of the field. If this method is successful, it returns ER_OK.

How do you set up a private field in a reflection?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

How do you set a field value in Java?

The set() method of java. lang. reflect. Field is used to set the value of the field represented by this Field object on the specified object argument to the specified new value passed as parameter.

How do you set Java to private?

We can't assign private to outer class and interface. The best use of private keyword is to create a fully encapsulated class in Java by making all the data members of that class private. If we make any class constructor private, we cannot create the instance of that class from outside the class.


2 Answers

Try this (inspired by Find a private field with Reflection?):

var prop = s.GetType().GetField("id", System.Reflection.BindingFlags.NonPublic     | System.Reflection.BindingFlags.Instance); prop.SetValue(s, "new value"); 

My changes were to use the GetField method - you are accessing a field and not a property, and to or NonPublic with Instance.

like image 160
nick_w Avatar answered Sep 21 '22 15:09

nick_w


Evidently, adding BindingFlags.Instance seems to have solved it:

> class SomeClass   {       object id;        public object Id       {           get           {               return id;           }       }   } > var t = typeof(SomeClass)       ; > t [Submission#1+SomeClass] > t.GetField("id") null > t.GetField("id", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); > t.GetField("id", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance) [System.Object id] >  
like image 31
Alxandr Avatar answered Sep 21 '22 15:09

Alxandr