gpt4 book ai didi

Java 泛型 : Is this safe enough?

转载 作者:行者123 更新时间:2023-11-29 09:48:37 25 4
gpt4 key购买 nike

考虑以下代码片段:

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)调用它当然。

问候。

最佳答案

一个简单的答案是忘记 EnumConverter 而是使用 InvoiceStatus.valueOf(rs.getString(9));

关于Java 泛型 : Is this safe enough?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17810280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com