Sunday, July 24, 2005

Using reflection to access private data

One day I ordered an expensive SDK to use additional functionality with previously purchased application. I was promised I could access certain additional features. This was not true. The method we needed to use was private.No big deal. Using reflection, we can see / view / access a private member, private variable, private method. You can also call a private method of another class. This is great to take a peek at some private data for the curious. Some people may say this is not a solution, dangerous, and also complain your messing up the laws of encapsulation. It worked for me. Here is an example that may help you. Take special note of the ORed bindingflags NonPublic and Instance because you wont find the private methods without them.

This is also useful for unit testing private methods.


using System;
using System.Reflection;
public class PrivateReflection
{
public static int Main()
{
ClassA a = new ClassA();
Console.WriteLine("before:" + readPrivateVar(a));
changePrivateVar(a, "I am changed!");
Console.WriteLine("after:" + readPrivateVar(a));
Console.WriteLine("executing:" + execPrivMethod(a, "haxx0red", 1234));
return 0;
}
public static string readPrivateVar(ClassA a)
{
Type t = Type.GetType("ClassA");
FieldInfo Myfieldinfoa = t.GetField("privateString",
BindingFlags.NonPublic | BindingFlags.Instance);
return (string)Myfieldinfoa.GetValue(a);
}
public static void changePrivateVar(ClassA a, string ChangeTo)
{
Type t = a.GetType();
FieldInfo f = t.GetField("privateString",
BindingFlags.NonPublic | BindingFlags.Instance);
f.SetValue(a, ChangeTo);
}
public static string execPrivMethod(ClassA a, string str, int integ)
{
Type t = a.GetType();
Object[] paramz = { str, integ };
MethodInfo m = t.GetMethod("privateCalculation",
BindingFlags.NonPublic | BindingFlags.Instance);
return (string)m.Invoke(a, paramz);
}
}
public class ClassA
{
private string privateString = "I am a private string.";
private string privateCalculation(string x, int y)
{
return x + "SECRET" + y.ToString();
}
}


Result:
before:I am a private string.
after:I am changed!
executing:haxx0redSECRET1234

4 Comments:

At 5:35 AM, Anonymous Anonymous said...

Reflection is great.
visit www.mgt4all.blogspot.com

 
At 2:40 PM, Anonymous mradul pandey said...

i can do it in easy way mannnn. ye baccho ka khel hai....

 
At 3:50 AM, Anonymous RS Gold said...

Nothing is achievable, if you set your cardiovascular system into it, you may be successful on the world, think about it! I think it can be done.

 
At 5:13 AM, Blogger hou said...

he method we needed to use was private.No big deal. Using reflection, we can see / view / access a private member.
xiaomi mi5 review
meizu m2 note
meizu mx5

 

Post a Comment

<< Home