我知道Java具有这些serval关键字来标识开发期间的变量范围,但是我想知道当它在生产环境中还是仅出于编码人员的兴趣时,这是否有所不同?谢谢。
可访问性也在运行时强制执行。如果某些代码试图访问不应访问的成员,则将抛出IllegalAccessException
或IllegalAccessError
。这是一个快速演示:
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;
// ^^^^^^^^^^^^
// To be changed to secretNumber in bytecode editor after compilation
System.out.println("Number read: " + a);
}
private static void reflection() throws IllegalAccessException, NoSuchFieldException {
AccessTest instance = new AccessTest();
AccessTest.class.getDeclaredField("publicNumber").get(instance); // <-- Works
try {
AccessTest.class.getDeclaredField("secretNumber").get(instance); // <-- Throws IllegalAccessException
} catch (IllegalAccessException e) {
System.out.println("Caught IllegalAccessException");
}
}
}
实际上,以上程序输出:
Caught IllegalAccessException
Number read: 10
当我使用字节码编辑器进行更改时
getfield com/blah/access/AccessTest/publicNumber I
在方法noReflection()
上:
getfield com/blah/access/AccessTest/secretNumber I
输出为:
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)
正如Michael提到的,此行为可能取决于JVM。我继续
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句