考虑以下代码片段:
public interface FieldEnum {
public String getEnumName();
}
public enum InvoiceStatus implements FieldEnum {
UNCHECKED("unchecked"),
ERROR("error"),
OK("ok");
private final String enumName;
private InvoiceStatus(final String enumName) {
this.enumName = enumName;
}
@Override
public String getEnumName() {
return enumName;
}
}
private InvoiceBean(final Integer invoiceId, final Integer businessPartnerId, final String invoiceNumber, final Date invoiceDate, final BigDecimal priceExclVAT, final BigDecimal VAT, final BigDecimal priceInclVAT, final BigDecimal paymentDiscount, final InvoiceStatus status) {
this.invoiceId = invoiceId;
this.businessPartnerId = businessPartnerId;
this.invoiceNumber = invoiceNumber;
this.invoiceDate = invoiceDate;
this.priceExclVAT = priceExclVAT;
this.VAT = VAT;
this.priceInclVAT = priceInclVAT;
this.paymentDiscount = paymentDiscount;
this.status = status;
}
public InvoiceBean(final ResultSet rs) throws SQLException {
this(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getDate(4), rs.getBigDecimal(5), rs.getBigDecimal(6), rs.getBigDecimal(7), rs.getBigDecimal(8), EnumConverter.convert(rs.getString(9), InvoiceStatus.values()));
}
下面的代码安全吗?
public class EnumConverter {
public static <T extends FieldEnum> T convert(String enumName, T[] enumValues) {
for (T enumValue : enumValues) {
if (enumName.equals(enumValue.getEnumName())) {
return enumValue;
}
}
throw new IllegalStateException("orm.enums.EnumConverter.convert: No suitable enum has been found. enumName = " + enumName + " fieldEnums = " + enumValues);
}
}
或者使用它会有什么好处?(注意添加Class<T> clazz
参数)
public class EnumConverter {
public static <T extends FieldEnum> T convert(String enumName, T[] enumValues, Class<T> clazz) {
for (T enumValue : enumValues) {
if (enumName.equals(enumValue.getEnumName())) {
return enumValue;
}
}
throw new IllegalStateException("orm.enums.EnumConverter.convert: No suitable enum has been found. enumName = " + enumName + " fieldEnums = " + enumValues);
}
}
EnumConverter.convert(rs.getString(9), InvoiceStatus.values(), InvoiceStatus.class)
然后通过当然调用它。
问候。