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