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 "";
}
}