Search code examples
javaclassloader

java.lang.IllegalAccessError: tried to access field ConcreteEntity.instance from class Entity


java.lang.IllegalAccessError: tried to access field ConcreteEntity.instance from class Entity

Ok so here is the deal. I am trying to access ConcreteEntity.instance which is a field with the access type default that exists inside the default ClassLoader and the Entity.getInstance is a method that exist in a child ClassLoader.

Now keep in mind they're both in the same package, however an IllegalAccessError is being thrown. Is there a solution to this problem that doesn't involve me actually loading the Entity class inside the same ClassLoader as ConcreteEntity?

0 new #14 <Entity>
 3 dup
 4 aload_0
 5 invokevirtual #18 <Adapter.getInstance>
 8 checkcast #20 <sl>
11 getfield #24 <sl.d>
14 invokespecial #25 <Entity.<init>>
17 areturn

The bytecode retrieved via jclasslib at were the exception is generated "After being compiled".

Thank you Gamb for cleaning up the post.


Solution

  • See my answer to a similar question, except in your case it is clear that you are dealing with multiple classloaders:

    The jvm considers classes loaded from different classloaders to be in different "runtime packages", even if they have the same package name. Quoting from the JVM specification, section 5.3:

    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.

    And in section 5.4.4:

    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 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.