【发布时间】:2016-11-20 22:51:56
【问题描述】:
我在一个方法中声明了一个本地类,其字段被声明为私有。但是,我仍然可以直接从封闭方法的主体中访问它们——这是为什么呢?
作为旁注,我已将匿名类中的所有字段声明为私有,但这样做实际上有什么好处吗?有什么东西可以访问它们吗?
编辑:代码示例
public void myMethod() {
class myException extends SomeOtherException{
private boolean Bool;
public Boolean getBool() { return this.Bool; }
public myException() { //constructor stuff }
}
try {
Thing.setHandler(new HandlingClass() {
private String myString; //What is the point in making these private?
... other methods in anonymous class ...
}
... more code ...
} catch (myException e) {
... e.Bool //Can be accessed. Why?
}
}
【问题讨论】:
-
制作
myString私人没有任何目的;反射行为略有不同(如果安装了 SecurityManager)。请注意,您可以这样做new HandlingClass() { ... }.myString
标签: java access-control anonymous-class local-class