매거 유형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의 첫 번째 매개 변수는 클래스입니다. 클래스마다 클래스의 대상이기 때문에 클래스를 작성합니다. 여기서Size를 사용할 수 있습니다.class
반환 유형은 하나의 클래스가 필요하고 매개 변수는 하나의 클래스의Class가 필요합니다.
들어오는name은 클래스에 정의되어 있어야 합니다. 예를 들어 SMALL MEDIUM LARGE
 

좋은 웹페이지 즐겨찾기