枚举 + 动态 反射

创建枚举类:

public enum TableEnum {
     

    ENUMONE("key1","method1"),
    ENUMTWO("key2","method2"),
    ENUMTHREE("key3","method3"),
    ENUMFOUR("key4","method4"),
    ENUMFIVE("key5","method5");

    private String key;

    private String value;

    TableEnum() {
     
    }

    TableEnum(String key, String value) {
     
        this.key = key;
        this.value = value;
    }

    private String key() {
     
        return this.key;
    }

    private String value() {
     
        return this.value;
    }


    public static String getValue(String key) {
     
        TableEnum[] tableEnums = values();
        for (TableEnum tableEnum : tableEnums) {
     
            if (tableEnum.key().equals(key)) {
     
                return tableEnum.value();
            }
        }
        return null;
    }

}

通过方法 找到枚举类的 对应的值 在通过反射去掉方法

    public int createTable(String projectId,String tableName) {
     
        int count = 0;;
        String key = tableName.split("_")[2];
        String value = TableEnum.getValue(key);
        Class<? extends CreateTableServiceImpl> aClass = SpringUtils.getBean(CreateTableServiceImpl.class).getClass();
        try {
     
            Method method = aClass.getMethod(value, String.class);
            method.invoke(aClass.newInstance(),tableName);
            count = 1;
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        return count;
    }

你可能感兴趣的:(java)