Java Enum Type

枚举类型的应用:

在Automation Framework中,经常会用枚举类定义一些或带属性或不带属性的常量,非常方便读取常量及其属性,所以深入了解一下枚举类型。
例如:

public enum ResourcePaths {
    
    
RETRIEVER_DOCUMENT("/shared/document/");
    private String resourcePath;
    ResourcePaths(String e) {
    
    
        resourcePath = e;
    }
    /**
     * getResourcePath
     *
     * @return resourcePath
     */
    public String getResourcePath() {
    
    
        return resourcePath;
    }
}

访问常量的属性:

String resource = ResourcePaths.valueOf(“RETRIEVER_DOCUMENT”).getResourcePath();

或则:

String resource = ResourcePaths.RETRIEVER_DOCUMENT.getResourcePath();

Enum Types
枚举类型是一个特殊的数据类型,一个枚举类型是一个预定义的常量集合,一个枚举类型的变量就等于其中一个常量。

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

例如:因为是常量,所以用大写表示。

public enum Day {
    
    
    SUNDAY, 
    MONDAY, 
    TUESDAY, 
    WEDNESDAY,
    THURSDAY, 
    FRIDAY, 
    SATURDAY 
}

注意:所有的枚举类型都继承于java的Enum Class,因为单继承原则,一个枚举类型不能再继承其它类。

Note: All enums implicitly extend java.lang.Enum. Because a class can only extend one parent (see Declaring Classes), the Java language does not support multiple inheritance of state (see Multiple Inheritance of State, Implementation, and Type), and therefore an enum cannot extend anything else.

根据Java规则,常量定义优先于任何成员变量和方法,因此存在成员变量和方法时,枚举常量应该以分号结束

Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.

扫描二维码关注公众号,回复: 12718852 查看本文章

注意:枚举类型的构造函数必须是private或则是Default的,常量都是最开始预定义在枚举体内,不可在外调用枚举的构造函数。

Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.

例如:除了构造函数,其它方法可以申明public,在包外也可以调用。

public enum Planet {
    
    
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
    
    
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() {
    
     return mass; }
    private double radius() {
    
     return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
    
    
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
    
    
        return otherMass * surfaceGravity();
    }
    public static void main(String[] args) {
    
    
        if (args.length != 1) {
    
    
            System.err.println("Usage: java Planet <earth_weight>");
            System.exit(-1);
        }
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
}

运行结果:

$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413

枚举类型原理:
为了深入了解枚举类的构建原理,我用Java Decompiler将枚举类进行了反编译。javap是JDK提供的一个命令行工具,javap能对给定的class文件提供的字节代码进行反编译。

C:\test>javac Planet.java
C:\test>javap Planet.class
Compiled from "Planet.java"
public final class Planet extends java.lang.Enum<Planet> {
    
    
  public static final Planet MERCURY;
  public static final Planet VENUS;
  public static final Planet EARTH;
  public static final Planet MARS;
  public static final Planet JUPITER;
  public static final Planet SATURN;
  public static final Planet URANUS;
  public static final Planet NEPTUNE;
  public static final double G;
  public static Planet[] values();
  public static Planet valueOf(java.lang.String);
  double surfaceGravity();
  double surfaceWeight(double);
  public static void main(java.lang.String[]);
  static {
    
    };
}

得出结论:

  1. 继承自Enum类,单继承原则,不可继承自其它类,可以现实接口
  2. 是final的,不可被继承
  3. 常量是枚举类的静态final成员,且是枚举类的一个实例
  4. 编译器为我们自动增加了values()和valueof(String name)方法。
    public static Planet[ ] values():返回包含了所有枚举常量的数组。
    public static Planet valueof(String name): 返回指定名字的枚举常量。

猜你喜欢

转载自blog.csdn.net/wumingxiaoyao/article/details/109706023
今日推荐