JAVA 通过string值和int值 获取枚举对象
调用方法:
int dType=Integer.parseInt(Long.toString(fdList.get(j).getDatatype()));
//调用方法一
dbfieldtype dbfdType=this.intToEnum(dbfieldtype.class,dType);
//调用方法二
dbfdType=dbfieldtype.codeOf(dType);
//Enum.valueOf(dbfieldtype.class,Long.toString(dType));
tableObj.fields.get(i).type=dbfdType;
//定义的枚举类型
import java.io.Serializable;
public enum dbfieldtype implements Serializable {
Int(1),
decimal(3),
string(4),
datetime(5),
date(6),
time(7),
binary(8),
bool(13),
geometry(14),
undefine(-1);
//
private int code=4;
dbfieldtype(int code){
this.code=code;
}
public int getCode()
{
return code;
}
public int getValue()
{ //此方法必须定义,转换时需要调用此方法
return code;
}
public static dbfieldtype codeOf(int code) {
for (dbfieldtype fdType : values()) {
if (fdType.getValue() == code) {
return fdType;
}
}
throw new RuntimeException("没有找到对应的枚举");
}
}
定义转换函数:
转换函数参考地址:https://blog.csdn.net/yuanwenyan/article/details/83824308
//
public <T extends Enum<T>> T stringToEnum(Class<T> enumType,
String value) {
T t = null;
try {
for (T ele:enumType.getEnumConstants()) {
if (enumType.getMethod("getValue").invoke(ele).equals(value)){
t = ele;
break;
}
}
} catch (Exception e) {
//e.printStackTrace();
this.printMsg(e.getMessage());
}
return t;
}
public <T extends Enum<T>> T intToEnum(Class<T> enumType,
int value) {
T t = null;
try {
for (T ele:enumType.getEnumConstants()) {
if (enumType.getMethod("getValue").invoke(ele).equals(value)){
t = ele;
break;
}
}
} catch (Exception e) {
//e.printStackTrace();
this.printMsg(e.getMessage());
}
return t;
}
//