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

前端 未结 4 949
北恋
北恋 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: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.

提交回复
热议问题