您的位置:首页 > 编程语言 > Java开发

Java中enum枚举实现原理

2016-04-10 00:00 585 查看
摘要: Java中enum枚举实现原理,其实在jdk的实现中,enum是继承了java.lang.Enum

Java中enum枚举实现原理,其实在jdk的实现中,enum是继承了java.lang.Enum,可以通过javap -verbose class查看字节码来分析,先上enum的测试案例代码。

顺便也熟悉下class的文件格式。

package org.sun.sample.pojo;

public enum EnumSample {

RED(1),
BLUE(2),
GREEN(3);

private long index;

private EnumSample(long index) {
this.index = index;
}

public long getIndex() {
return index;
}

public void setIndex(long index) {
this.index = index;
}
}


package org.sun.sample;

import org.sun.sample.pojo.EnumSample;

public class Bootstrap {
public static void main(String[] args) {
System.out.println(EnumSample.BLUE.getIndex());
EnumSample.BLUE.setIndex(9999);
System.out.println(EnumSample.BLUE.getIndex());
}
}


通过代码可以看出来,其实enum和普通的类没有什么区别,唯一不同的是enum的构造函数是private,所以不能通过传统的new的方式来创建enum,其实这种实现方式也是jdk的一种讨巧方式吧。
我们通过javap -verbose EnumSample来看下这个类中的字节码。

Classfile /Users/M/workspace/eclipse/sun-sample/target/classes/org/sun/sample/pojo/EnumSample.class
Last modified 2016-4-10; size 1356 bytes
MD5 checksum d1bff701b1550835772a3718869463c0
Compiled from "EnumSample.java"
public final class org.sun.sample.pojo.EnumSample extends java.lang.Enum<org.sun.sample.pojo.EnumSample>
minor version: 0
major version: 49
flags: ACC_PUBLIC, ACC_FINAL, ACC_SUPER, ACC_ENUM#(这里设置了访问权限)
Constant pool:#(常量池)
#1 = Class              #2             // org/sun/sample/pojo/EnumSample
#2 = Utf8               org/sun/sample/pojo/EnumSample
#3 = Class              #4             // java/lang/Enum
#4 = Utf8               java/lang/Enum
#5 = Utf8               RED
#6 = Utf8               Lorg/sun/sample/pojo/EnumSample;
#7 = Utf8               BLUE
#8 = Utf8               GREEN
#9 = Utf8               index
#10 = Utf8               J
#11 = Utf8               ENUM$VALUES
#12 = Utf8               [Lorg/sun/sample/pojo/EnumSample;
#13 = Utf8               <clinit>
#14 = Utf8               ()V
#15 = Utf8               Code
#16 = String             #5             // RED
#17 = Methodref          #1.#18         // org/sun/sample/pojo/EnumSample."<init>":(Ljava/lang/String;IJ)V
#18 = NameAndType        #19:#20        // "<init>":(Ljava/lang/String;IJ)V
#19 = Utf8               <init>
#20 = Utf8               (Ljava/lang/String;IJ)V
#21 = Fieldref           #1.#22         // org/sun/sample/pojo/EnumSample.RED:Lorg/sun/sample/pojo/EnumSample;
#22 = NameAndType        #5:#6          // RED:Lorg/sun/sample/pojo/EnumSample;
#23 = String             #7             // BLUE
#24 = Long               2l
#26 = Fieldref           #1.#27         // org/sun/sample/pojo/EnumSample.BLUE:Lorg/sun/sample/pojo/EnumSample;
#27 = NameAndType        #7:#6          // BLUE:Lorg/sun/sample/pojo/EnumSample;
#28 = String             #8             // GREEN
#29 = Long               3l
#31 = Fieldref           #1.#32         // org/sun/sample/pojo/EnumSample.GREEN:Lorg/sun/sample/pojo/EnumSample;
#32 = NameAndType        #8:#6          // GREEN:Lorg/sun/sample/pojo/EnumSample;
#33 = Fieldref           #1.#34         // org/sun/sample/pojo/EnumSample.ENUM$VALUES:[Lorg/sun/sample/pojo/EnumSample;
#34 = NameAndType        #11:#12        // ENUM$VALUES:[Lorg/sun/sample/pojo/EnumSample;
#35 = Utf8               LineNumberTable
#36 = Utf8               LocalVariableTable
#37 = Methodref          #3.#38         // java/lang/Enum."<init>":(Ljava/lang/String;I)V
#38 = NameAndType        #19:#39        // "<init>":(Ljava/lang/String;I)V
#39 = Utf8               (Ljava/lang/String;I)V
#40 = Fieldref           #1.#41         // org/sun/sample/pojo/EnumSample.index:J
#41 = NameAndType        #9:#10         // index:J
#42 = Utf8               this
#43 = Utf8               getIndex
#44 = Utf8               ()J
#45 = Utf8               setIndex
#46 = Utf8               (J)V
#47 = Utf8               values
#48 = Utf8               ()[Lorg/sun/sample/pojo/EnumSample;
#49 = Methodref          #50.#52        // java/lang/System.arraycopy:(Ljava/lang/Object;ILjava/lang/Object;II)V
#50 = Class              #51            // java/lang/System
#51 = Utf8               java/lang/System
#52 = NameAndType        #53:#54        // arraycopy:(Ljava/lang/Object;ILjava/lang/Object;II)V
#53 = Utf8               arraycopy
#54 = Utf8               (Ljava/lang/Object;ILjava/lang/Object;II)V
#55 = Utf8               valueOf
#56 = Utf8               (Ljava/lang/String;)Lorg/sun/sample/pojo/EnumSample;
#57 = Methodref          #3.#58         // java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
#58 = NameAndType        #55:#59        // valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
#59 = Utf8               (Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
#60 = Utf8               SourceFile
#61 = Utf8               EnumSample.java
#62 = Utf8               Signature
#63 = Utf8               Ljava/lang/Enum<Lorg/sun/sample/pojo/EnumSample;>;
{
public static final org.sun.sample.pojo.EnumSample RED;
descriptor: Lorg/sun/sample/pojo/EnumSample;
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL, ACC_ENUM

public static final org.sun.sample.pojo.EnumSample BLUE;
descriptor: Lorg/sun/sample/pojo/EnumSample;
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL, ACC_ENUM

public static final org.sun.sample.pojo.EnumSample GREEN;
descriptor: Lorg/sun/sample/pojo/EnumSample;
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL, ACC_ENUM
#static这里正式初始化RED,BLUE,GREEN
static {};
descriptor: ()V
flags: ACC_STATIC
Code:
stack=6, locals=0, args_size=0
0: new           #1                  // class org/sun/sample/pojo/EnumSample
3: dup
4: ldc           #16                 // String RED
6: iconst_0
7: lconst_1
8: invokespecial #17                 // Method "<init>":(Ljava/lang/String;IJ)V
11: putstatic     #21                 // Field RED:Lorg/sun/sample/pojo/EnumSample;
14: new           #1                  // class org/sun/sample/pojo/EnumSample
17: dup
18: ldc           #23                 // String BLUE
20: iconst_1
21: ldc2_w        #24                 // long 2l
24: invokespecial #17                 // Method "<init>":(Ljava/lang/String;IJ)V
27: putstatic     #26                 // Field BLUE:Lorg/sun/sample/pojo/EnumSample;
30: new           #1                  // class org/sun/sample/pojo/EnumSample
33: dup
34: ldc           #28                 // String GREEN
36: iconst_2
37: ldc2_w        #29                 // long 3l
40: invokespecial #17                 // Method "<init>":(Ljava/lang/String;IJ)V
43: putstatic     #31                 // Field GREEN:Lorg/sun/sample/pojo/EnumSample;
46: iconst_3
47: anewarray     #1                  // class org/sun/sample/pojo/EnumSample
50: dup
51: iconst_0
52: getstatic     #21                 // Field RED:Lorg/sun/sample/pojo/EnumSample;
55: aastore
56: dup
57: iconst_1
58: getstatic     #26                 // Field BLUE:Lorg/sun/sample/pojo/EnumSample;
61: aastore
62: dup
63: iconst_2
64: getstatic     #31                 // Field GREEN:Lorg/sun/sample/pojo/EnumSample;
67: aastore
68: putstatic     #33                 // Field ENUM$VALUES:[Lorg/sun/sample/pojo/EnumSample;
71: return
LineNumberTable:
line 5: 0
line 6: 14
line 7: 30
line 3: 46
LocalVariableTable:
Start  Length  Slot  Name   Signature

public long getIndex();
descriptor: ()J
flags: ACC_PUBLIC
Code:
stack=2, locals=1, args_size=1
0: aload_0
1: getfield      #40                 // Field index:J
4: lreturn
LineNumberTable:
line 16: 0
LocalVariableTable:
Start  Length  Slot  Name   Signature
0       5     0  this   Lorg/sun/sample/pojo/EnumSample;

public void setIndex(long);
descriptor: (J)V
flags: ACC_PUBLIC
Code:
stack=3, locals=3, args_size=2
0: aload_0
1: lload_1
2: putfield      #40                 // Field index:J
5: return
LineNumberTable:
line 20: 0
line 21: 5
LocalVariableTable:
Start  Length  Slot  Name   Signature
0       6     0  this   Lorg/sun/sample/pojo/EnumSample;
0       6     1 index   J

public static org.sun.sample.pojo.EnumSample[] values();
descriptor: ()[Lorg/sun/sample/pojo/EnumSample;
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=5, locals=3, args_size=0
0: getstatic     #33                 // Field ENUM$VALUES:[Lorg/sun/sample/pojo/EnumSample;
3: dup
4: astore_0
5: iconst_0
6: aload_0
7: arraylength
8: dup
9: istore_1
10: anewarray     #1                  // class org/sun/sample/pojo/EnumSample
13: dup
14: astore_2
15: iconst_0
16: iload_1
17: invokestatic  #49                 // Method java/lang/System.arraycopy:(Ljava/lang/Object;ILjava/lang/Object;II)V
20: aload_2
21: areturn
LineNumberTable:
line 1: 0
LocalVariableTable:
Start  Length  Slot  Name   Signature

public static org.sun.sample.pojo.EnumSample valueOf(java.lang.String);
descriptor: (Ljava/lang/String;)Lorg/sun/sample/pojo/EnumSample;
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=1, args_size=1
0: ldc           #1                  // class org/sun/sample/pojo/EnumSample
2: aload_0
3: invokestatic  #57                 // Method java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
6: checkcast     #1                  // class org/sun/sample/pojo/EnumSample
9: areturn
LineNumberTable:
line 1: 0
LocalVariableTable:
Start  Length  Slot  Name   Signature
}
SourceFile: "EnumSample.java"
Signature: #63                          // Ljava/lang/Enum<Lorg/sun/sample/pojo/EnumSample;>;


在字节码中,我们可以看到enum关键字修饰的枚举,自动继承了java.lang.Enum类。

我们在看下java.lang.Enum的源代码。

/*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/

package java.lang;

import java.io.Serializable;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;

/**
* This is the common base class of all Java language enumeration types.
*
* More information about enums, including descriptions of the
* implicitly declared methods synthesized by the compiler, can be
* found in section 8.9 of
* <cite>The Java™ Language Specification</cite>.
*
* <p> Note that when using an enumeration type as the type of a set
* or as the type of the keys in a map, specialized and efficient
* {@linkplain java.util.EnumSet set} and {@linkplain
* java.util.EnumMap map} implementations are available.
*
* @param <E> The enum type subclass
* @author  Josh Bloch
* @author  Neal Gafter
* @see     Class#getEnumConstants()
* @see     java.util.EnumSet
* @see     java.util.EnumMap
* @since   1.5
*/
public abstract class Enum<E extends Enum<E>>
implements Comparable<E>, Serializable {
/**
* The name of this enum constant, as declared in the enum declaration.
* Most programmers should use the {@link #toString} method rather than
* accessing this field.
*/
private final String name;

/**
* Returns the name of this enum constant, exactly as declared in its
* enum declaration.
*
* <b>Most programmers should use the {@link #toString} method in
* preference to this one, as the toString method may return
* a more user-friendly name.</b>  This method is designed primarily for
* use in specialized situations where correctness depends on getting the
* exact name, which will not vary from release to release.
*
* @return the name of this enum constant
*/
public final String name() {
return name;
}

/**
* The ordinal of this enumeration constant (its position
* in the enum declaration, where the initial constant is assigned
* an ordinal of zero).
*
* Most programmers will have no use for this field.  It is designed
* for use by sophisticated enum-based data structures, such as
* {@link java.util.EnumSet} and {@link java.util.EnumMap}.
*/
private final int ordinal;

/**
* Returns the ordinal of this enumeration constant (its position
* in its enum declaration, where the initial constant is assigned
* an ordinal of zero).
*
* Most programmers will have no use for this method.  It is
* designed for use by sophisticated enum-based data structures, such
* as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
*
* @return the ordinal of this enumeration constant
*/
public final int ordinal() {
return ordinal;
}

/**
* Sole constructor.  Programmers cannot invoke this constructor.
* It is for use by code emitted by the compiler in response to
* enum type declarations.
*
* @param name - The name of this enum constant, which is the identifier
*               used to declare it.
* @param ordinal - The ordinal of this enumeration constant (its position
*         in the enum declaration, where the initial constant is assigned
*         an ordinal of zero).
*/
protected Enum(String name, int ordinal) {
this.name = name;
this.ordinal = ordinal;
}

/**
* Returns the name of this enum constant, as contained in the
* declaration.  This method may be overridden, though it typically
* isn't necessary or desirable.  An enum type should override this
* method when a more "programmer-friendly" string form exists.
*
* @return the name of this enum constant
*/
public String toString() {
return name;
}

/**
* Returns true if the specified object is equal to this
* enum constant.
*
* @param other the object to be compared for equality with this object.
* @return  true if the specified object is equal to this
*          enum constant.
*/
public final boolean equals(Object other) {
return this==other;
}

/**
* Returns a hash code for this enum constant.
*
* @return a hash code for this enum constant.
*/
public final int hashCode() {
return super.hashCode();
}

/**
* Throws CloneNotSupportedException.  This guarantees that enums
* are never cloned, which is necessary to preserve their "singleton"
* status.
*
* @return (never returns)
*/
protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

/**
* Compares this enum with the specified object for order.  Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object.
*
* Enum constants are only comparable to other enum constants of the
* same enum type.  The natural order implemented by this
* method is the order in which the constants are declared.
*/
public final int compareTo(E o) {
Enum<?> other = (Enum<?>)o;
Enum<E> self = this;
if (self.getClass() != other.getClass() && // optimization
self.getDeclaringClass() != other.getDeclaringClass())
throw new ClassCastException();
return self.ordinal - other.ordinal;
}

/**
* Returns the Class object corresponding to this enum constant's
* enum type.  Two enum constants e1 and  e2 are of the
* same enum type if and only if
*   e1.getDeclaringClass() == e2.getDeclaringClass().
* (The value returned by this method may differ from the one returned
* by the {@link Object#getClass} method for enum constants with
* constant-specific class bodies.)
*
* @return the Class object corresponding to this enum constant's
*     enum type
*/
@SuppressWarnings("unchecked")
public final Class<E> getDeclaringClass() {
Class<?> clazz = getClass();
Class<?> zuper = clazz.getSuperclass();
return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;
}

/**
* Returns the enum constant of the specified enum type with the
* specified name.  The name must match exactly an identifier used
* to declare an enum constant in this type.  (Extraneous whitespace
* characters are not permitted.)
*
* <p>Note that for a particular enum type {@code T}, the
* implicitly declared {@code public static T valueOf(String)}
* method on that enum may be used instead of this method to map
* from a name to the corresponding enum constant.  All the
* constants of an enum type can be obtained by calling the
* implicit {@code public static T[] values()} method of that
* type.
*
* @param <T> The enum type whose constant is to be returned
* @param enumType the {@code Class} object of the enum type from which
*      to return a constant
* @param name the name of the constant to return
* @return the enum constant of the specified enum type with the
*      specified name
* @throws IllegalArgumentException if the specified enum type has
*         no constant with the specified name, or the specified
*         class object does not represent an enum type
* @throws NullPointerException if {@code enumType} or {@code name}
*         is null
* @since 1.5
*/
public static <T extends Enum<T>> T valueOf(Class<T> enumType,
String name) {
T result = enumType.enumConstantDirectory().get(name);
if (result != null)
return result;
if (name == null)
throw new NullPointerException("Name is null");
throw new IllegalArgumentException(
"No enum constant " + enumType.getCanonicalName() + "." + name);
}

/**
* enum classes cannot have finalize methods.
*/
protected final void finalize() { }

/**
* prevent default deserialization
*/
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
throw new InvalidObjectException("can't deserialize enum");
}

private void readObjectNoData() throws ObjectStreamException {
throw new InvalidObjectException("can't deserialize enum");
}
}

源代码分享:http://git.oschina.net/weizheng2015/sun-sample
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: