JAVA 通过string值和int值 获取枚举对象说明

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;
    }
    //
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值