为什么不能在方法中本地声明枚举? [英] Why can't enums be declared locally in a method?

查看:27
本文介绍了为什么不能在方法中本地声明枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我发现自己在编写这样的代码......

Today, I found myself coding something like this ...

public class LocalEnums {

    public LocalEnums() {
    }

    public void foo() {
        enum LocalEnum {
            A,B,C
        };

        // ....
        // class LocalClass { }

    }
}

当编译器报告本地enum错误时,我有点惊讶:

and I was kind of surprised when the compiler reported an error on the local enum:

成员枚举 LocalEnum 不能是本地

The member enum LocalEnum cannot be local

为什么不能像那样将枚举声明为本地的?

Why can't enums be declared local like classes?

我发现这在某些情况下非常有用.在我工作的情况下,其余的代码不需要知道关于 enum 的任何信息.

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.

是否存在任何结构/设计冲突来解释为什么这是不可能的,或者这可能是 Java 的未来特性?

Is there any structural/design conflict that explains why this is not possible or could this be a future feature of Java?

推荐答案

枚举是静态嵌套类,因为它们定义了静态成员变量(枚举值),而这内部类不允许:http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.3

更新:我正在查看 JLS(java 语言规范)以获取有关静态嵌套类限制的更多详细信息,并且没有找不到它(尽管它可能在那里,隐藏在不同的主题下).从纯粹的实现角度来看,没有理由不能做到这一点.所以我怀疑这是一个语言哲学问题:不应该这样做,因此不会得到支持.但我当时不在,所以纯属猜测.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆