Why can you reflect and call a (not so) private method in Java and .Net

c#, java, reflection, scope

Solution

In both Java and .NET, this is only allowed if you have sufficient permissions. Code that you run directly from the command line is (usually) operating in "full trust" mode. If you try doing the same thing in more restrictive environments, it will fail. Access control is more about encapsulation than security though. If you're operating at full trust, you've probably got enough access to launch native methods to poke around memory directly anyway...

Why is it allowed? Sometimes it can be handy. It should be treated with care, but it can be useful.

What are the ramifications? Your code becomes fragile; you're interacting with a type in a way it doesn't expect.

Should it be taken away in a future version of the language? It's a platform feature rather than a language feature in the first place, but no I don't think it should be removed.

Do other languages/platforms allow this? I'm not sure... I wouldn't be surprised though.

Problem

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.

Original source