Availability also applies at runtime. If any code tries to access a member that it should not, then an IllegalAccessException or IllegalAccessError . Here is a quick demo:
public class AccessTest { public int publicNumber; private int secretNumber; } public class Client { public static void main(String[] args) throws Exception { reflection(); noReflection(); } private static void noReflection() throws IllegalAccessException, NoSuchFieldException { int a = new AccessTest().publicNumber;
With reflection:
Be that as it may, the above program outputs:
Caught IllegalAccessException Number read: 10
Without reflection:
When I use the bytecode editor to change
getfield com/blah/access/AccessTest/publicNumber I
in the noReflection() to method:
getfield com/blah/access/AccessTest/secretNumber I
output:
Caught IllegalAccessException Exception in thread "main" java.lang.IllegalAccessError: tried to access field com.blah.access.AccessTest.secretNumber from class com.blah.access.Client at com.blah.access.Client.noReflection(Client.java) at com.blah.access.Client.main(Client.java:12)
As Michael noted, this behavior may be JVM dependent. I ran it on
java version "1.6.0_20" Java(TM) SE Runtime Environment (build 1.6.0_20-b02) Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)
oksayt
source share