Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 279
Justin Avatar asked Dec 28 '12 13:12

Justin


2 Answers

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

like image 150
Jörn Horstmann Avatar answered Oct 23 '22 04:10

Jörn Horstmann


Javadoc: Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.

As I think that some difficult class manipulation is attempted, maybe class loading, invest some time in how both classes are loaded. (In rare cases an explicit serialVersionId might help.)

If the classes are related (super / subclass), then try to remove that relation using an interface. Possibly use injection. That is not refer/load a class twice.

Sorry a concrete answer I cannot give.

like image 1
Joop Eggen Avatar answered Oct 23 '22 05:10

Joop Eggen