IllegalAccessError, packages and classloaders

Ever wondered why you get an IllegalAccessError when invoking protected/package-private methods on class B from class A although both classes are in the same package?

Well it mostly happens only at runtime when two different classloaders loading the classes. classloader A loads class A, classloader B loads class B. Since the JVM spec, paragraph 5.3 mandates

At runtime, a class or interface is determined not by its name alone, but by a pair: its binary name (§4.2.1) 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.

the package from class A is the same as class B at compile time, but NOT at runtime since it was loaded by different classloaders! To get to the root cause, you have to check why your classes are loaded by different classloaders. For example I came across that problem when using JBoss 7 the first time.