Java:枚舉的不同返回類型 (Java: Different return type by enum)


問題描述

Java:枚舉的不同返回類型 (Java: Different return type by enum)

我想知道是否可以有多個返回類型,這些返回類型由方法中的枚舉參數給出。

例如:

public <T extends ICloudServer> T startServer(ServerType type) {
  ...
}

如果服務器類型是 PROXY ,我想返回一個 ProxyServer,如果服務器類型是 MINECRAFT,我想返回一個 MinecraftServer。

有沒有辦法用 Java 來實現?


參考解法

方法 1:

Make servers implement ICloudServer interface and add start method into ServerType enum to be server starting‑up strategy method. Different server has different configuration and start up procedures.

class Minecraft implements ICloudServer{

    //ctor
    Minecraft(ServerConfig cfg){
         //ctor implementations
    } 

    //Other implementation details
}

public enum ServerType {

    MINECRAFT { 
        @Override
        public ICloudServer start(ServerConfig cfg ) {      
            //Apply config for minecraft
            Minecraft server = new Minecraft(cfg.port()).username(cfg.username()).password(cfg.password()).done();
             //Start minecraft server 
            server.start();
            return  server;
        }
    },

    PROXY {
        @Override
        public ICloudServer start(ServerConfig cfg) { 
            //Apply config and start proxy server
            ProxyServer server = new ProxyServer(cfg);           
            return server;
        }
    };
    public abstract ICloudServer start(ServerConfig port) throws Exception;
}

As @JB Nizet mentioned change startServer method return type to ICloudServer and simply call ServerType#start(ServerConfig cfg) to start the server.

public ICloudServer startServer(ServerType type) {  

    try{
       return type.start(new ServerConfig());
    }catch(Exception ex){
        //log exception
    }

    throw new ServerStartException("failed to start server");
}

(by DominicAwan Biru)

參考文件

  1. Java: Different return type by enum (CC BY‑SA 2.5/3.0/4.0)

#java #return #generics #types






相關問題

電子郵件地址中帶有 + 字符的 Java 郵件 (Java mail with + character in email address)

如何快速原型化 Java 代碼? (How to quickly prototype Java code?)

如何使用 Maven 在目標(SVN-)服務器上創建 Javadoc? (How to create Javadoc on the target (SVN-) server using Maven?)

為什麼檢查二叉樹有效性的解決方案不起作用? (Why the solution for checking the validity of binary tree is not working?)

Selenium webdriver通過第一個數字找到texy (Selenium webdriver find texy by first digits)

setOnClickListener 沒有在圖像視圖上被調用 (setOnClickListener is not getting called on image view)

繪製多邊形:找不到錯誤 (Drawing Polygon : unable to find error)

半透明 JButton:對像出現在背景中 (Semi-Transparent JButton: Objects appear in Background)

比較同一數組的元素 (Compare elements of the same array)

Java 屏幕截圖小程序 (Java screen capture applet)

Minecraft 1.8.9 Forge Modding 的Java 開發工具包,需要什麼JDK/JRE,代碼是否正確? (Java Development Kit with Minecraft 1.8.9 Forge Modding, What JDK/JRE Is Needed, Is Code Correct?)

java while (resultset.next()) 不返回同一列中的所有數據 (java while (resultset.next()) does not return all data in the same column)







留言討論