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

In Java and C #, you can call a private method through reflection (as shown below).

  • Why is this allowed?
  • What are the consequences of this?
  • Should it be selected in a future version of the language?
  • Do other languages ​​/ platforms allow? If I have this class in Java and C #

Here is an example

public class Foo
{
    private void say() { WriteToConsoleMethod("Hello reflected world"); }
}

where WriteToConsole()depends on the language, then I can run the following to call the private method say():

FROM#

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, this is not obvious, but it is also not difficult.

+3
source share
4 answers

Java .NET , . , , " ". , . - , . , , , , , ...

  • ? . , .

  • ? ; , .

  • ? , , , .

  • /? ... , .

+17

, .

, - , -, , .

+4

- , (, - / ), Code Access Security .net. runtime , Authenticode.

+1

// ++ , ++ , .

, , ; , , , IDE , , , .

, , - , . // , , , . - ( ), - , . , , , .. . .

, , , , , , , EASIER , . .

.Net Reflector, , , , private. , , , , .

-1

Source: https://habr.com/ru/post/1718814/


All Articles