java枚举类小结

  |   0 评论   |   1,309 浏览

测试类源码:

package main.test3;

public enum AAA {
	jj1("1"),
	jj2("2");
	public static final AAA[] VALUES = new AAA[]{jj1,jjj2};
	AAA(String a){
		System.out.println(a);
	}
}

反编译后:

public final class main.test3.AAA extends java.lang.Enum<main.test3.AAA> {
  public static final main.test3.AAA jj1;
  public static final main.test3.AAA jj2;
  public static final main.test3.AAA[] VALUES;
  public static main.test3.AAA[] values();
  public static main.test3.AAA valueOf(java.lang.String);
  static {};
}

测试类源码:

package main.test3;

public class Main {
	public static void main(String[] args) {
		
		System.out.println(AAA.jj1);
		System.out.println(AAA.jj2);
		AAA.values();
		
		System.out.println(AAA.VALUES);
		for (AAA a : AAA.VALUES) {
			System.out.println(a);
		}
	}
	
}

带着几个问题来了解枚举类

1. 枚举类中反编译后values方法是哪里来的?

在jdk文档中有描述.
https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Java programming language enum types are much more powerful than their counterparts in other languages. The `enum` declaration defines a _class_ (called an _enum type_). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static `values` method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the `Planet` class example below iterates over all the planets in the solar system.

其中说到
编译器在创建枚举时自动添加一些特殊方法。例如,它们有一个静态values方法,该方法返回一个数组,其中包含枚举的所有值,按声明的顺序排列

2. 枚举类中values是如何实现的?

通过反编译发现源码中

private static final AAA[] $VALUES = new AAA[]{jj1, jj2};
package main.test3;

public enum AAA {

   jj1("1"),
   jj2("2");
   public static final AAA[] VALUES = new AAA[]{jj1};
   // $FF: synthetic field
   private static final AAA[] $VALUES = new AAA[]{jj1, jj2};

   private AAA(String var3) {
      System.out.println(var3);
   }

}

其实values返回的就是一个AAA类的数组

3. 枚举类中是如何初始化的?

通过上面测试类的代码执行的结果看

1
2
jj1
jj2
jj1

由反编译代码中得知,每一个都是static变量,其实在jvm加载枚举类的时候,对其中的每个属性都调用了枚举类AAA的构造函数
从而达到初始化的过程.

评论

发表评论

validate