2014-01-22 29 views
1

我有一個字符串一個枚舉的屬性是這樣的:如何獲取枚舉中的字符串值?

public enum CategoriaRischio { 
    a1a1("classificati in cat. III e IV,o contenenti gas instabili appartenenti alla cat. dalla I alla IV"), 
    a1a2("classificati in cat. I e II"), 
    a1a5("liquidi appartenenti a cat. I,II e III"), 
    a1b1("Gas compressi, liquefatti, disciolti o vapori diversi dal vapor d'acqua in cat.III e IV, recipienti di vapore d'acqua e d'acqua surriscaldata in cat. da I a IV"), 
    a1b2("Gas compressi, liquefatti, disciolti o vapori diversi dal vapor d'acqua in cat.I e II"); 

    private String descrizioneCategoria; 

    public String getDescrizioneCategoria() { 
     return descrizioneCategoria; 
    } 

    private CategoriaRischio(final String descrizioneCategoria){ 
     this.descrizioneCategoria = descrizioneCategoria; 
    } 

} 

我想表明在JSP頁面中的字符串值。 我該怎麼做?

+0

您無法通過EL參考常量。因此,您將無法通過EL代碼訪問Enum。 http://www.javaranch.com/journal/200601/Journal200601.jsp#a3將幫助您構建自定義標籤並通過EL訪問常量。 –

回答

1

您可以使用這樣的格式:

public class MyFormatter implements Formatter<CategoriaRischio> 
{ 

    @Override 
    public String print(CategoriaRischio cat, Locale locale) 
    { 
    return cat.getCategoriaRischio(); 
    } 

    @Override 
    public CategoriaRischio parse(String text, Locale locale) throws ParseException 
    { 
    return CategoriaRischio.valueOf(text); 
    } 
} 

然後你必須在你的servlet上下文註冊格式,以這樣的方式

<mvc:annotation-driven conversion-service="conversionService"> 
     </mvc:annotation-driven> 

     <!-- Custom formatters --> 
     <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 
     <property name="formatters"> 
      <set> 
      <bean class= "yourPackage.MyFormatter" /> 
      </set> 
     </property> 
     </bean> 
+2

您的'parse'實現看起來像是從其他問題複製的,並且與問題不匹配 - 無論如何'print'實現看起來不錯 – Ralph

+1

您有理由..我從我的代碼複製了這個:) – Teo

1

我已經實現了打印的Printer(所以你可以將Enum轉換成字符串,但不能反過來。

在下面的代碼中,你會發現一個例子,其中的字符串/名稱/值/如何 - 喲u-call-it,取自MessageSource(消息屬性文件) - 這允許支持多種語言。

public class EnumToStringPrinter implements Printer<Enum<?>> { 

    /** Use the same immutable value instead of creating an new array every time. */ 
    private static final Object[] NO_PARAM = new Object[0]; 

    /** The prefix of all message codes. */ 
    private static final String PREFIX = "label_"; 

    /** The separator in the message code, between different packages as well as between package can class. */ 
    private static final String PACKAGE_SEPARATOR = "_"; 

    /** The separator in the message code, between the class name and the enum case name. */ 
    private static final String ENUM_CASE_SEPARATOR = "_"; 

    /** The message source. */ 
    private MessageSource messageSource; 

    @Autowired 
    public EnumToStringPrinter(final MessageSource messageSource) { 
     if(messageSource == null) { 
      throw new RuntimeException("messageSource must not be null"); 
     } 

     this.messageSource = messageSource; 
    } 

    @Override 
    public String print(final Enum<?> source, final Locale locale) { 
     /* locale null can mean default locale, this depends on the messageSource implmentation */ 
     if (source != null) { 
      String enumValueName = source.name(); 
      String code = PREFIX + source.getClass().getName().toLowerCase().replace(".", PACKAGE_SEPARATOR) 
        + ENUM_CASE_SEPARATOR + enumValueName.toLowerCase(); 

      String message = messageSource.getMessage(code, NO_PARAM, enumValueName, locale); 

      return message; 
     } else { 
      return ""; 
     } 
    }  
} 

Printer S中的市長缺點是,它是很難在春季進行註冊。爲此我實施了Printer2ConverterAdapter。和所使用的適配器註冊Printer像X->字符串Converter

/** 
* Adapter that adapts a {@link Printer} to an Converter, more correct to an {@link GenericConverter}. 
* 
* Follows the Object Adapter pattern: 
* <ul> 
* <li>Adaptor - this class</li> 
* <li>Target - {@link GenericConverter}</li> 
* <li>Adaptee - the Printer {@link #Printer2ConverterAdapter(Printer)}</li> 
* </ul> 
* 
* @author Ralph 
*/ 
public class Printer2ConverterAdapter implements GenericConverter { 

    private final Class<?> printerObjectType; 

    @SuppressWarnings("rawtypes") 
    private final Printer printer; 

    public <T> Printer2ConverterAdapter(final Printer<T> printer) { 
     this.printerObjectType = resolvePrinterObjectType(printer); 
     this.printer = printer; 
    } 

    @Override 
    public Set<ConvertiblePair> getConvertibleTypes() { 
     return Collections.singleton(new ConvertiblePair(this.printerObjectType, String.class)); 
    } 

    @SuppressWarnings("unchecked") 
    @Override 
    public Object convert(final Object source, final TypeDescriptor sourceType, final TypeDescriptor targetType) { 
     if (source == null) { 
      return ""; 
     } 
     return this.printer.print(source, LocaleContextHolder.getLocale()); 
    } 

    private Class<?> resolvePrinterObjectType(final Printer<?> printer) { 
     return GenericTypeResolver.resolveTypeArgument(printer.getClass(), Printer.class); 
    } 

    @Override 
    public String toString() { 
     return this.printerObjectType.getName() + " -> java.lang.String : " + this.printer; 
    } 

}