如何在枚举中获取字符串值?

时间:2014-01-22 09:19:53

标签: spring jsp

我有一个带有这样的String属性的枚举:

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页面中显示字符串值。 我怎么能这样做?

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

我已经实现了Printer用于打印(因此您可以将Enum转换为字符串,但不是相反。

在下面的代码中,您将找到一个示例,其中String / Name / Value / How-ever-you-call-it取自MessageSource(消息属性文件) - 这允许支持多种语言。 / p>

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的市长缺点是,在Spring中很难注册它们。因此我实施了Printer2ConverterAdapter。并使用适配器将Printer注册为X-&gt; String 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;
    }

}