Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use reflection to invoke a private method?

There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType); dynMethod.Invoke(this, new object[] { methodParams }); 

In this case, GetMethod() will not return private methods. What BindingFlags do I need to supply to GetMethod() so that it can locate private methods?

like image 407
Jeromy Irvine Avatar asked Sep 25 '08 19:09

Jeromy Irvine


People also ask

How do you call a private method using 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.

Can we access private methods using reflection C#?

Using reflection in C# language, we can access the private fields, data and functions etc.

Is it possible to get information about private fields methods using reflection?

Yes it is possible.


1 Answers

Simply change your code to use the overloaded version of GetMethod that accepts BindingFlags:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType,      BindingFlags.NonPublic | BindingFlags.Instance); dynMethod.Invoke(this, new object[] { methodParams }); 

Here's the BindingFlags enumeration documentation.

like image 89
wprl Avatar answered Oct 22 '22 10:10

wprl