【问题标题】:How to access enum if inner enum having same name exist如果存在具有相同名称的内部枚举,如何访问枚举
【发布时间】:2015-05-26 18:31:03
【问题描述】:

无法访问定义在类 Test 之外的枚举中的值。

如何访问 Reddel、Jonathan、Goldendel 等枚举常量

enum Apple{
    Reddel,Jonathan,Goldendel,Winesap,Cortland;
}


public class Test{
    enum Apple{
        Seb,Majj,Dlred,Wipe,Cland;
    }
    public static void main(String s[]){
        //here I want to access enumeration constant from Apple outside Test.
        //Apple.Winesap
        //Apple.Goldendel
        System.out.println(Apple.Winesap);

    }
}

【问题讨论】:

  • 使用整个路径。
  • Apple.Winesap 之前应该附加什么,因为这是在同一个包中。
  • .Apple vs .Test.Apple

标签: java enums


【解决方案1】:

如果你有你的类在一个包中,说

package pkg;

然后使用pkg.Apple.Winesap 将起作用。 (另一个Apple的全称是pkg.Test.Apple。)

您也可以从pkg.Apple静态导入成员:

import static pkg.Apple.*;

然后使用Winesap

如果您使用的是默认包(没有包声明),那么内部的 Apple 会遮蔽另一个 Apple,那么您就不走运了。 (静态导入也是如此;您不能从默认包中的类中静态导入成员。)

相关问题:

【讨论】:

  • 这些在默认包中,无需附加
  • 那么恐怕你不走运了,正如我在上一段中所说的那样。
【解决方案2】:

应附加包名。

【讨论】:

  • 在这种情况下,外部Apple 存在于默认包中,即没有包声明。
  • 使用默认包是一种不好的风格,会导致这样的问题。不要这样做。
【解决方案3】:

您需要指定完整的包路径。我测试的以下代码正在编译:

package com.my.test;

enum Apple{
    Reddel,Jonathan,Goldendel,Winesap,Cortland;
}

public class Test{
    enum Apple{
        Seb,Majj,Dlred,Wipe,Cland;
    }
    public static void main(String s[]){
        //here I want to access enumeration constant from Apple outside Test.
        //Apple.Winesap
        //Apple.Goldendel
        System.out.println(com.my.test.Apple.Winesap);
        }
    }

【讨论】:

  • 在这种情况下,外部 Apple 存在于默认包中,即没有包声明。
【解决方案4】:

枚举在某处声明,想象在ClassName.java 中。您可以分别使用ClassName.Apple.ReddelTest.Apple.Seb 引用它们

【讨论】:

  • 但是外部的Apple 不在Test 类中,所以我不明白这是怎么可能的。
  • 在哪个类中声明了外部Apple
  • 它是一个顶级类,所以它没有被声明为任何类中。
  • 所以不改名字就不能引用外部枚举
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 2020-04-05
  • 1970-01-01
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
相关资源
最近更新 更多