简体   繁体   English

尝试在 groovy 中编写一个通用的 enum util 类

[英]Trying to write a generic enum util class in groovy

Problem问题

We have multiple enum types that have some public static EnumType valueOfText(String text) , for the purpose of mapping the contents of a data file cell to enum.我们有多个枚举类型,它们具有一些public static EnumType valueOfText(String text) ,目的是将数据文件单元格的内容映射到枚举。

I'm trying to write a generic enum util that takes a comma-separated string and return multiple enum values.我正在尝试编写一个通用的枚举实用程序,它采用逗号分隔的字符串并返回多个枚举值。 For example, we have the following enum:例如,我们有以下枚举:

public enum Frequency {
    SEMI_ANNUAL("S"), MONTHLY("M"), QUARTERLY("Q"), ANNUAL("A")

    public final String textValue;

    public Frequency(String textValue) {
        this.textValue = textValue;
    }

    public static Frequency valueOfText(String textValue) {
        for (Frequency frequency : values()) {
            if (frequency.textValue.equals(textValue))
                return frequency;
        }
        return null;
    }
}

and string "A,S" which we want to convert to [Frequency.ANNUAL, Frequency.SEMI_ANNUAL] .和我们想要转换为[Frequency.ANNUAL, Frequency.SEMI_ANNUAL]字符串"A,S"

Attempted solution尝试的解决方案

I create some EnumUtils like so:我像这样创建了一些EnumUtils

import java.util.stream.Collectors

public final class EnumUtils {
    public static final String LIST_SEPARATOR = ",";

    public static <E extends Enum<E>> List<E> CreateFromText(String text) {
        List<String> textList = text.split(this.LIST_SEPARATOR)

        return textList.stream()
                .map { txt ->
                    E.valueOfText(txt)
                }
                .collect(Collectors.toList())
    }
}

What happen after said solution上述解决方案后会发生什么

We go to use it, like this:我们去使用它,像这样:

EnumUtils.CreateFromText<Frequency>(row[3])

and the IDE compain, immediately, about the <> .和 IDE compain,立即,关于<>

How can we specify enum type in this?我们如何在此指定枚举类型?

In Groovy you can do it if you pass the actual Class instead of just using a type parameter.在 Groovy 中,如果传递实际的Class而不是仅使用类型参数,则可以执行此操作。

enum Frequency {
    SEMI_ANNUAL("S"), MONTHLY("M"), QUARTERLY("Q"), ANNUAL("A")

    final String textValue;

    Frequency(String textValue) {
        this.textValue = textValue;
    }

    static Frequency valueOfText(String textValue) {
        return values().find { it.textValue == textValue }
    }
}

final class EnumUtils {
    static <E extends Enum<E>> List<E> createFromText(Class<E> clazz, String text) {
        return text.split(",").collect { clazz.valueOfText(it) }
    }
}
EnumUtils.createFromText(Frequency, "S,M")

The same idea won't work in Java, since clazz won't have valueOfText at compile time.同样的想法在 Java 中不起作用,因为clazz在编译时没有valueOfText

Perhaps the Util class doesn't save you much typing, though:不过,也许 Util 类不会为您节省太多输入:

"S,M".split(",").collect(Frequency.&valueOfText)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM