In both Java and C# it is possible to invoke a private method via reflection (as shown below).
- Why is this allowed?
- What are the ramifications of doing this?
- Should it be taken away in a future version of the language?
- Do other languages/platforms allow this?If I have this class in both Java and C#
Here is the example
public class Foo
{
private void say() { WriteToConsoleMethod("Hello reflected world"); }
}
where WriteToConsole()
is language specific, then I can run the following to call the private say()
method:
C#
Foo f = new Foo();
var fooType = f.GetType();
var mi = fooType.GetMethod("say", BindingFlags.NonPublic | BindingFlags.Instance);
mi.Invoke(f, null);
Java
Foo f = new Foo();
Method method = f.getClass().getDeclaredMethod("say", null);
method.setAccessible(true);
method.invoke(f, null);
As you can see, it is not obvious, but it's not difficult either.