使用枚举代替case,同时调用不同的方法

1、整体实现思路

1、根据枚举动态获取方法名。
2、通过反射执行对应的方法。

2、实现方法

    @Test
    public void test5(){
        //获得的值
        String code = "456";

        Class<TestDemo> testDemoClass = TestDemo.class;
        try {
            //根据枚举的value动态调用方法
            TestDemo testDemo = testDemoClass.getDeclaredConstructor().newInstance();
            Method test1 = testDemoClass.getDeclaredMethod(TestEnum.getValueByCode(code));
            String result = (String) test1.invoke(testDemo);
            System.out.println("方法执行结果result=="+result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    //方法一
    private String test6(){
        return "123";
    }

    //方法二
    private String test7(){
        return "456";
    }

3、使用的枚举类

package com.sinoguarantee.domain.enums;

import lombok.Getter;
import org.junit.Test;

/**
 * @author Sonny
 * @create 2022/12/26
 * @desc
 */
@Getter
public enum TestEnum {


    SUCCESSDONE("123","test6"),

    ERRORDONE("456","test7");


    private String code;
    private String value;

    TestEnum(String code, String value) {
        this.code = code;
        this.value = value;
    }

    /**
     * 通过Code取枚举
     *
     * @param code
     * @return
     */
    public static TestEnum getTypeByCode(String code) {
        for (TestEnum enums : TestEnum.values()) {
            if (enums.getCode().equals(code)) {
                return enums;
            }
        }
        return null;
    }

    /**
     * 通过code取描述
     *
     * @param code
     * @return
     */
    public static String getValueByCode(String code) {
        for (TestEnum enums : TestEnum.values()) {
            if (enums.getCode().equals(code)) {
                return enums.getValue();
            }
        }
        return "";
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值