为什么不能在一个方法中本地声明枚举? [英] Why can't enums be declared locally in a method?
问题描述
今天,我发现自己编写这样的东西...
public class LocalEnums {
/ pre>
public LocalEnums(){
}
public void foo(){
枚举LocalEnum {
A,B,C
};
// ....
// class LocalClass {}
}
}
当编译器报告本地
枚举错误
时,我感到非常惊讶:
会员枚举LocalEnum不能
本地
为什么不能将枚举本地声明为类?
我发现这在某些方面非常有用的情况。在我工作的情况下,其余的代码不需要知道关于
枚举的任何内容。
。
是否有任何结构/设计冲突,这解释了为什么这是不可能的,或者这可能是Java的未来功能?
解决方案枚举是静态嵌套类,因为它们定义静态成员变量(枚举值),这是不允许内部类: http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.3
更新:我正在查看
JLS
( java语言规范),了解更多有关限制的详细信息静态嵌套类,并没有找到它(虽然它可能在那里,隐藏在不同的主题下)。从纯实施的角度来看,没有理由不能做到这一点。所以我怀疑这是一个语言哲学问题:不应该做,所以不会得到支持。但是我不在,所以这是纯粹的猜测。
作为评论:如果你的方法足够大,他们需要自己的枚举那么这是一个强有力的标志,你需要重构。
Today, I found myself coding something like this ...
public class LocalEnums { public LocalEnums() { } public void foo() { enum LocalEnum { A,B,C }; // .... // class LocalClass { } } }
and I was kind of surprised when the compiler reported an error on the local
enum
:The member enum LocalEnum cannot be local
Why can't enums be declared local like classes?
I found this very useful in certain situations. In the case I was working, the rest of the code didn't need to know anything about the
enum
.Is there any structural/design conflict that explains why this is not possible or could this be a future feature of Java?
解决方案Enums are static nested classes because they define static member variables (the enum values), and this is disallowed for inner classes: http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.3
Update: I was looking through the
JLS
(java language specification) for more detail on the restrictions of static nested classes, and didn't find it (although it's probably there, hidden under a different topic). From a pure implementation perspective, there's no reason that this couldn't be done. So I suspect that it was a language philosophy issue: it shouldn't be done, therefore won't be supported. But I wasn't there, so that's pure speculation.As a comment: if your methods are large enough that they require their own enums, then it's a strong sign that you need refactoring.
这篇关于为什么不能在一个方法中本地声明枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!