有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何创建具有关联值(如Swift enum)的Java枚举?

编辑: 明确地说,我不是在问如何在java中执行枚举。我想问的是,java中是否有什么东西可以补充Enum中与Swifts关联的值。这不仅仅是如何在枚举上存储值。看看我提供的例子,你会发现其中的区别

因此,一位iOS开发人员向我展示了一个使用swifts enum关联值的架构。这个概念对我来说似乎很有趣,作为一名安卓开发人员,我很好奇在java中是否可以做到不太冗长。Java枚举的等价物是什么?还是不可能

下面是我所说的关联值的一个例子。它是从apple docs.

enum Barcode {
    case UPCA(Int, Int, Int, Int)
    case QRCode(String)
}

// Instantiated
var productBarcode = Barcode.UPCA(8, 85909, 51226, 3)
// or
productBarcode = .QRCode("ABCDEFGHIJKLMNOP")


switch productBarcode {
case .UPCA(let numberSystem, let manufacturer, let product, let check):
    println("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case .QRCode(let productCode):
    println("QR code: \(productCode).")
}

共 (1) 个答案

  1. # 1 楼答案

    我也很难回答这个问题,并提出了以下解决方案。值得注意的是,我甚至不使用枚举,因为Java的枚举不太适合这个任务。重要的一点是,对于案例,您需要类似switch的行为,每个案例中都有相关的值

    类枚举类型

    public abstract class Barcode
    {
        private Barcode() {}
    
        void caseUPCA(IntFunction<IntFunction<IntFunction<IntConsumer>>> action) {}
        void caseQRCode(Consumer<String> action) {}
    
        static Barcode UPCA(int numberSystem, int manufacturer, int product, int check)
        {
            return new Barcode()
            {
                @Override public void caseUPCA(IntFunction<IntFunction<IntFunction<IntConsumer>>> action)
                {
                    action.apply(numberSystem).apply(manufacturer).apply(product).accept(check);
                }
            };
        }
    
        static Barcode QRCode(String text)
        {
            return new Barcode()
            {
                @Override public void caseQRCode(Consumer<String> action)
                {
                    action.accept(text);
                }
            };
        }
    }
    

    演示应用程序

    public class BarcodeMain
    {
        public static void main(String[] args) throws Exception
        {
            List<Barcode> barcodes = new ArrayList<>();
            barcodes.add(Barcode.UPCA(8, 85909, 51226, 3));
            barcodes.add(Barcode.QRCode("foobar"));
    
            for(Barcode barcode: barcodes)
            {
                barcode.caseUPCA(numberSystem -> manufacturer -> product -> check ->
                    System.out.printf("UPC-A: %d, %d, %d, %d%n", numberSystem, manufacturer, product, check));
                barcode.caseQRCode(productCode ->
                    System.out.printf("QR code: %s%n", productCode));
            }
        }
    }
    

    输出

    UPC-A: 8, 85909, 51226, 3
    QR code: foobar
    

    专业人士

    • 与基于枚举的解决方案相比,实现代码要少得多
    • 与基于枚举的解决方案相比,使用站点上的代码更少

    缺点

    • Barcode实现中有很多笨拙的嵌套。只是因为爪哇很丑
    • 不能从切换案例操作中抛出异常
    • UPCA实现中,由于有许多参数,角括号盲。为了防止这种情况泄漏到API中,可以声明一个public interface UPCAConsumer extends IntFunction<IntFunction<IntFunction<IntConsumer>>> {},并使用UPCAConsumer作为caseUPCA(action)参数类型