Java枚舉以及實現原理

不要讓這個世界的複雜性阻礙你的前進。 要成爲一個行動主義者,將解決人類的不平等視爲己任。 它將成爲你生命中最重要的經歷之一。
——比爾·蓋茨在哈佛大學的演講

聲明枚舉

[public]enum 枚舉類型名稱[implements 接口名稱列表]
{
	枚舉值;
	變量成員聲明及初始化;
	方法聲明及方法體;
}

簡單的例子:

/**
 * 簡單的枚舉類型舉例
 * @author wangbaofu
 * 
 */
public class ScoreTester {
	public static void main(String[] args) {
		giveScore(Score.EXCELLENT);
	}
	private static void giveScore(Score s) {
		switch (s) {
		case EXCELLENT:
			System.out.println("Excellent");
			break;
		case QUALIFIED:
			System.out.println("Qualified");
			break;
		case FAILED:
			System.out.println("Failed");
			break;
		default:
			break;
		}
	}
}
enum Score {
	EXCELLENT, QUALIFIED, FAILED;
}
/*
 * 輸出 Excellent
 * */

通過jad反編譯一下:

// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   ScoreTester.java

package enum_;


final class Score extends Enum
{

    private Score(String s, int i)
    {
        super(s, i);
    }

    public static Score[] values()
    {
        Score ascore[];
        int i;
        Score ascore1[];
        System.arraycopy(ascore = ENUM$VALUES, 0, ascore1 = new Score[i = ascore.length], 0, i);
        return ascore1;
    }

    public static Score valueOf(String s)
    {
        return (Score)Enum.valueOf(enum_/Score, s);
    }

    public static final Score EXCELLENT;
    public static final Score QUALIFIED;
    public static final Score FAILED;
    public static final Score ADD;
    private static final Score ENUM$VALUES[];

    static 
    {
        EXCELLENT = new Score("EXCELLENT", 0);
        QUALIFIED = new Score("QUALIFIED", 1);
        FAILED = new Score("FAILED", 2);
        ADD = new Score("ADD", 3);
        ENUM$VALUES = (new Score[] {
            EXCELLENT, QUALIFIED, FAILED, ADD
        });
    }
}

枚舉的特點:

  • 枚舉定義實際上是定義了一個類
  • 所有枚舉類型都隱含繼承(擴展)自Java.lang.Enum,因此枚舉類型不能再繼承任何其它類
  • 枚舉類型中的類可以包括方法和變量
  • 枚舉類型的構造方法必須是包內私有或者私有的。定義在枚舉開頭的常量會自動創建,不能顯示地調用枚舉類的構造方法。

枚舉類型的默認方法

  • 靜態的values()方法用於獲得枚舉類型的枚舉值的數組
  • toString方法返回枚舉值的字符串描述
  • valueOf方法將以字符串形式表示的枚舉值轉化爲枚舉類型的對象
  • Ordinal方法獲得對象在枚舉類型中的位置索引

最佳實踐 (該部分內容爲《編寫高質量代碼之java》學習筆記)

下邊貼一下jdk中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&trade; 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");
    }
}

推薦使用枚舉定義常量

常量聲明是每一個項目都不可或缺的,在Java 1.5之前,
我們只有兩種方式的聲明:類常量和接口常量,若在項目中
使用的是Java 1.5之前的版本基本上都是如此定義的。不過,
在1.5版以後有了改進,即新增了一種常量聲明方式: 枚舉聲明常量
枚舉聲明常量的優點
**(1)**枚舉常量更簡單
**(2)**枚舉常量屬於穩態型
**(3)**枚舉具有內置方法
是java.lang.Enum的子類,該基類提供了諸如獲得排序值的ordinal方法、compareTo比較方法等,大大簡化了常量的訪問。
**(4)**枚舉可以自定義方法
舉常量不僅可以定義靜態方法,還可以定義非靜態方法,而且還能夠從根本上杜絕常量類被實例化。

	package enumtest;
/**
 * 枚舉的優勢
 *
 */
public class TestSeason {
	public static void main(String[] args) {
//		通過values方法獲得所有的枚舉項
		for (Season s : Season.values()) {
			System.out.println(s);
		}
	}
}
enum Season{
	Spring,Summer,Autumn,Winter;
}
interface SeasonIntece{
	int Spring=0;
	int Summer=1;
	int Autumn=2;
	int Winter=3;
}

使用構造函數協助描述枚舉項

枚舉的屬性:排序號,其默認值爲0,1,2,3…
枚舉描述:含義通過枚舉的構造函數,聲明每個枚舉項(也就是枚舉的實例)
必須具有屬性和行爲,這是對枚舉的描述和補充,目的是使,枚舉項表述的意義更加清晰準確

	enum Season {
	Spring("春"), Summer("夏"), Autumn("秋"), Winter("冬");
	private String desc;

	Season(String desc) {
		this.desc = desc;
	}
	// 自定義方法
	public static Season getComfortableSeason() {
		return Spring;
	}
//獲取枚舉描述
	public String getDesc() {
		return desc;
	}
}	

小心switch帶來的空值異常,處理方法增加空判斷

對於枚舉類型很多的情況下,在default中添加: throw
new AssertionError(“沒有該類型”);

使用valueOf前必須進行校驗

	package enumtest;

import java.util.Arrays;
import java.util.List;

public class ValueOfTest {
	public static void main(String[] args) {
		List<String> params = Arrays.asList("EXCELLENT", "aDD");
		for (String name : params) {
			// 查找直面值與name相同的枚舉 項
			
//			添加代碼
			if(Score.contains(name)){
				Score s = Score.valueOf(name);
				if (s != null) {
					// 有該枚舉項時
					System.out.println(s);
				} else {
					// 沒有該枚舉項時
					System.out.println("無相關枚舉項");
				}
			}
			//			Score s = Score.valueOf(name);
//			if (s != null) {
//				// 有該枚舉項時
//				System.out.println(s);
//			} else {
//				// 沒有該枚舉項時
//				System.out.println("無相關枚舉項");
//			}
		}
	}

	enum Score {
		EXCELLENT, QUALIFIED, FAILED, ADD;
		// 是否包含枚舉項
		public static boolean contains(String name) {
			// 所有的枚舉值
			Score[] scores = values();
			// 遍歷查找
			for (Score s : scores) {
				if (s.name().equals(name))
					return true;
			}
			return false;
		}

	}
}
/*
 * Exception in thread "main" java.lang.IllegalArgumentException: No enum
 * constant enumtest.ValueOfTest.Score.aDD
 * 
 * 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 const"+enumType+"."+name); }
 */

(1) 枚舉非靜態方法實現工廠方法模式
用枚舉實現工廠方法模式更簡潔

package enumtest;

/**
 * 工廠方法模式(Factory Method Pattern)是“創建對象的接口,讓子類決定實例化哪一個類,並使一個類的實例化延遲到其子類”。
 * 工廠方法模式在我們的開發工作中經常會用到。
 * 這是最原始的工廠方法模式,有兩個產品:福特汽車和別克汽車,然後通過工廠方法模式來生產。有了工廠方法模式,我們就不用關心一輛車具體是怎麼生成的了
 * ,只要告訴工廠“給我生產一輛福特汽車”就可以了
 */
// 抽象產品
interface Car {
};

// 具體產品類
class FordCar implements Car {
};

// 具體產品類
class BuickCar implements Car {
};

// 工廠類
public class CarFactory {
	public static Car createCar(Class<? extends Car> c) {
		try {
			return c.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {

			e.printStackTrace();
		}
		return null;
	}
	public static void main(String[] args) {
//		生產車輛
		Car cat =CarFactory.createCar(FordCar.class);
	}
}
package enumtest;
//枚舉非靜態方法實現工廠方法模式
public class CarFactoryEnum {
	public static void main(String[] args) {
//		生產汽車
		Car car = CarFactoryEnum1.BuickCar.create();
		
	}
}

enum CarFactoryEnum1 {
	// 定義工廠類能生產汽車的類型
	FordCar, BuickCar;
	// 生產汽車
	public Car create() {
		switch (this) {
		case FordCar:
			return new FordCar();
		case BuickCar:
			return new BuickCar();
		default:
			throw new AssertionError("無效參數");
		}
	}
}

(2)通過抽象方法生成產品

enum CarFactory3{
	FordCar{
		public Car create(){
			return new FordCar();
		}
	},BuickCar{
		public Car create(){
			return new BuickCar();
		}
	};
//	首先定義一個抽象製造方法create,然後每個枚舉項自行實現。
	public abstract Car create();
}

用枚舉類型的工廠方法模式有以下三個優點:
(1)避免錯誤調用的發生
(2)性能好,使用便捷
枚舉類型的計算是以int類型的計算爲基礎的,這是最基本的操作,性能當
然會快,至於使用便捷,注意看客戶端的調用,代碼的字面意思就是“汽車
工廠,我要一輛別克汽車,趕快生產”。
(3)降低類間耦合
不管生產方法接收的是Class、String還是int的參數,都會成爲客戶端類的
負擔,這些類並不是客戶端需要的,而是因爲工廠方法的限制必須輸入的,
例如Class參數,對客戶端main方法來說,它需要傳遞一個FordCar.class
參數才能生產一輛福特汽車,除了在create方法中傳遞該參數外,業務類
不需要改Car的實現類。這嚴重違背了
迪米特
原則(Law of Demeter,簡稱爲
LoD
),也就是最少知識原則:一個對象應該對其他對象有最少的瞭解。
示例代碼



	/**

	 * 支付類型

	 */

	public enum PayType{



		typeUnknow("未知支付類型" , -1), typeAlipay("支付寶支付" , 4), typeWechatPay("微信支付" , 5);

		private String name;

		private int value;



		// 構造方法

		private PayType(String name, int value) {

			this.name = name;

			this.value = value;

		}

	}

我是IT小王,如果喜歡我的文章,可以掃碼關注我的微信公衆號
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章