Can't access protected member of superclass from same package in different jar

前端 未结 4 987
你的背包
你的背包 2020-12-31 09:05

I\'m having a strange problem that I can\'t figure out that popped up when trying to pluginize my program. An additional problem is that I\'m not able to create a simple tes

4条回答
  •  灰色年华
    2020-12-31 09:44

    OK, so with the help of axtavt and other respondents I figured out what the problem is. The other answers helped, but they didn't get it exactly right, which is why I'm answering my own question. The problem turned out to be the concept of "runtime packages", defined in the Java Virtual Machine specification as follows:

    5.3 Creation and Loading

    ... At run time, a class or interface is determined not by its name alone, but by a pair: its fully qualified name and its defining class loader. Each such class or interface belongs to a single runtime package. The runtime package of a class or interface is determined by the package name and defining class loader of the class or interface. ...

    5.4.4 Access Control

    ... A field or method R is accessible to a class or interface D if and only if any of the following conditions is true: ...

    • R is protected and is declared in a class C, and D is either a subclass of C or C itself.
    • R is either protected or package private (that is, neither public nor protected nor private), and is declared by a class in the same runtime package as D.

    The first clause explains why Road is allowed to access Seed.garden, since Road is a subclass of Seed, and the second clause explains why Road$4 is not allowed to access it, despite being in the same package as Road, since it is not in the same runtime package, having been loaded by a different class loader. The restriction is not actually a Java language restriction, it is a Java VM restriction.

    So the conclusion for my situation is that the exception occurs due to a legitimate restriction of the Java VM, and I'm going to have to work around it, probably by making the fields public, which is not a problem in this case since they are final, and not secret, or perhaps by exporting Seed.garden to Road$4 via Road, which does have access.

    Thank you everyone for your suggestions and answers!

提交回复
热议问题