JVM/Java, are method accessibility rules enforced at runtime?

前端 未结 4 901
北恋
北恋 2021-01-06 15:44

I was curious about how the JVM works. Does the JVM acknowledge method accesibility rules like \'private\' protected or is that only done at compile time?

For examp

相关标签:
4条回答
  • 2021-01-06 16:04

    To the JLS!

    15.12.4 Runtime Evaluation of Method Invocation
    At run time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. Third, the accessibility of the method to be invoked is checked. Fourth, the actual code for the method to be executed is located. Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code.

    The wording of the JLS indicates that the accessibility would be checked at runtime.

    0 讨论(0)
  • 2021-01-06 16:14

    The JVM does acknowledge these. They can be overridden, by calling setAccessible(true) as Prashant Bhate does, but by default they are enforced. (See http://download.oracle.com/javase/6/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible%28boolean%29.)

    By the way, you write that "the compiler doesn't encode type method visibility rules into the Java bytecde file"; but it does. In addition to the above, it has to encode these, for a number of reasons. For example:

    • you can compile a class A that references class B even if you only have the compiled version of class B.
    • you can inspect a method's visibility via reflection (the getModifiers() method).
    • private methods aren't virtual -slash- can't be overridden by subclasses.
    0 讨论(0)
  • 2021-01-06 16:15

    If you want to call this method from outside current class you could call private & protected methods using reflection.

    Method m = RunX.class.getDeclaredMethod("test3");
    m.setAccesible(true);
    m.invoke(u);
    

    however you can call this protected (and also private) method directly from main() without any issues.

    0 讨论(0)
  • 2021-01-06 16:25

    Oli mentioned it rightly that ultimately you can do anything if you come to extent of byte code manipulation (if done correctly !!!). Although I will like answer your question of accessibility honor at runtime in Java. If you have any doubts then please go ahead and use reflection to call the private method of one class from other class and you will get your answer. Java creates the function table of class at runtime when loading it and allow the refererence to the functions in limit of accessibility rule. However Java provides facility where you can call the private methods via reflection using setAccessible(true) on the method reference before invoking it.

    0 讨论(0)
提交回复
热议问题