枚举类型enum的使用

 

要有一个private的构造器   而且constant定义必须在最开始

 

package com.enums;

public enum Size
{
	//这个必须放在最开始
	SMALL("S"), MEDIUM("M"),LARGE("L");
	
	private String abbrev;
	public String getAbbrev(){
		return this.abbrev;
	}
	private Size(String abbrev){
		this.abbrev = abbrev;
	}
	
	public static void main(String[] args){
		for(Size s: Size.values()){
			System.out.println(s + "\t" + s.getAbbrev() + "\t" + s.toString());
		}
		
		System.out.println(Size.SMALL);
//		System.out.println(Size.valueOf("S"));
		System.out.println(Size.valueOf("SMALL"));
		System.out.println(Size.valueOf(Size.class, "SMALL"));
	}
}


 

源码

    /**
     * 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.) 
     *
     * @param enumType the <tt>Class</tt> 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 <tt>enumType</tt> or <tt>name</tt>
     *         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 const " + enumType +"." + name);
    }


这里的valueOf第一个参数是一个类,因为每个类都是Class的对象,所以写作 Class<T>, 这里可以使用Size.class

 而返回类型需要是一个类,参数需要是一个类的Class。

传入的name必须要在你的类中定义的有才可以,比如 SMALL   MEDIUM  LARGE

 

 

你可能感兴趣的:(String,object,null,Class,whitespace)