java如何通过反射获取枚举对象

public enum AccountType {
     
    BTC("1", "BTC", "比特币", "url"),
    ETH("2", "ETH", "以太坊", "url"),
    USDT("3", "USDT", "泰达币", "url");

    /**
     * 编号(id)
     */
    @Getter
    private final String id;

    /**
     * name
     */
    @Getter
    private final String code;

    /**
     * 描述
     */
    @Getter
    private final String desc;

    /**
     * 交易地址
     */
    @Getter
    private final String address;

    AccountType(String id, String code, String desc, String address) {
     
        this.id = id;
        this.code = code;
        this.desc = desc;
        this.address = address;
    }

    public static String getCoinAddress(String coinCode) throws Exception {
     
        //获取Class对象
        Class<?> clzz = AccountType.class;
        // 获取所有常量
        Object[] objects = clzz.getEnumConstants();
        //获取指定方法
        Method coinAddressAddress = clzz.getMethod("getAddress");
        Method coinAddressCode = clzz.getMethod("getCode");
        for (Object obj : objects) {
     
            if (coinAddressCode.invoke(obj) == coinCode) {
     
                 //根号有Enum对象.invoke(obj) 方式获取指定值
                return coinAddressAddress.invoke(obj).toString();
            }
        }
        return null;
    }
}

你可能感兴趣的:(Java,Java通过反射获取枚举对象,获取枚举对象,反射)