Accessing Private methods via reflection
At a recent Atlanta VB Study Group meeting, the topic of Reflection was presented. As part of the discussion, I mentioned that it is possible to call private methods from external classes. Unfortunately I stumbled briefly trying to demonstrate how to accomplish this. In the meeting, I attempted to modify the existing code. Below are the appropriate code snippets for demonstration purposes.
Public Class MyClass
Private Sub YouCantSeeMe()
MessageBox.Show("You shouldn't be here.")
End Sub
End Class
Public Class MyImplementer
Public Sub Main()
Dim obj As New MyClass
'Get a reference to the type of the object we can reflect on
Dim t As Type = GetType(MyClass)
'Get a handle on the method in question
'The next line doesn't work. See below for the correction
Dim mi As MethodInfo = t.GetMethod("YouCantSeeMe", _
BindingFlags.NonPublic + BindingFlags.Instance)
'Call the method
mi.Invoke(obj, Nothing)
End Sub
End Class
We weren't too far off. The key was we used the wrong operator to combine the binding flags. Instead of Anding (+) them, we should have ORed them. If we modify the mi instantiation line as below, we can successfully call into the private method from an external class, thereby breaking our object's encapsulation.
Dim mi As MethodInfo = t.GetMethod("YouCantSeeMe", _
BindingFlags.NonPublic OR BindingFlags.Instance)
comments powered by
Disqus