I have two classes.
Class A
has protected method m()
, a
is an instance of A
.
Class B
is in the same package as class A
.
I am trying to access a.m()
but I am getting IllegalAccessError
...
What's wrong?
I have two classes.
Class A
has protected method m()
, a
is an instance of A
.
Class B
is in the same package as class A
.
I am trying to access a.m()
but I am getting IllegalAccessError
...
What's wrong?
The compiler should catch errors like this. As you are apparently getting this at runtime, something odd has happened. Probably you have changed the source code but fully recompiled.
Another potential, but obscure, problem is loading the classes through different class loaders. Classes loaded from different class loaders will be in different packages even if the package name is the same (in the same way as classes with the same name loaded by different class loaders will be different classes).
This can happen if classes A and B are loaded by different classloader. The jvm then considers these classes to be in different "runtime packages". 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.
It has to work, see the following example that works just fine:
package com.stackoverflow;
public class TEST
{
static class A {
protected void m()
{
System.out.println("hello from A.m()");
}
}
static class B {
public B()
{
a.m();
}
private A a = new A();
}
/**
* @param args
*/
public static void main(String[] args)
{
B b = new B();
}
}
which prints out the intended message: "hello from A.m()
"
"The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package."
compiler should catch errors like this. As you are getting this at runtime, something wrong has been happened. Most probably you have changed the source code which is fully recompiled.
It must work. Here is a running example -
**
**
package com.test;
public class A {
protected void m(){
System.out.println("Hi Stackoverflow");
}
}
**
**
package com.test;
public class B{
public static void main(String[] args) {
A a = new A();
a.m();
}
}
which prints the expected string
Hi Stackoverflow