是否可以在switch语句中使用类?

时间:2012-01-11 22:25:25

标签: java

我正在使用Java 1.3进行移动设备开发而没有enum类型,因此我正在使用Typesafe Enum Pattern。 E.g。

public class DownloadEvent {

    //Download events
    public static final DownloadEvent DOWNLOAD_STARTED = new DownloadEvent("Download started");
    public static final DownloadEvent DOWNLOAD_COMPLETED = new DownloadEvent("Download completed");

    private String eventDescription;

    private DownloadEvent(String eventDescription){

        this.eventDescription = eventDescription;
    }

    public String toString(){
        return eventDescription;
    }
} 

这种方法的问题是编译器不允许在switch语句中使用类,例如

DownloadEvent event = getDownloadEvent(); //returns a download event

switch(event){
case DownloadEvent.DOWNLOAD_STARTED:
    //do some stuff
}

这有什么办法吗?或者我应该回到使用int常量列表

4 个答案:

答案 0 :(得分:3)

您可以为DownloadEvent提供一个可以使用getter检索的type-property(例如int),并在switch语句中使用该属性

DownloadEvent event = getDownloadEvent(); //returns a download event

switch(event.getType() ){
case DownloadEvent.DOWNLOAD_STARTED.getType():
    //do some stuff
}

但这当然不如使用枚举

那么好

答案 1 :(得分:2)

您可以在DownloadEvent类中使用静态变量进行计数。然后每个Downloadevent都可以拥有其uniqe id(构造函数中的id = counter++)。然后你可以做

 switch(event.id) {
 case DownloadEvent.DOWNLOAD_STARTED.id:

几乎无缝。

警告:阅读评论

答案 2 :(得分:1)

不,那是不可能的。 Java的switch语句只支持原始数据类型,枚举,字符串和一些特殊类(例如Integer)。

一种方法确实是回到使用int列表。另一种方法当然是使用if-then-else而不是switch:

if (DownloadEvent.DOWNLOAD_STARTEd.equals(event)) {}
else if ... 

答案 3 :(得分:0)

我建议您重构您的实施以使用Strategy pattern,而不是使用switchequalsinstanceof和朋友。它并不难,引入DownLoadEvent接口并创建两个类:

新界面:

interface DownloadEvent {
    void doStuff();
}

头等舱:

public class DownloadStartedEvent implements DownloadEvent {
    public void doStuff() {
        // does stuff that should happen when the download has started
    }
}

第二课:

public class DownloadCompletedEvent implements DownloadEvent {
    public void doStuff() {
        // does stuff that should happen when the download has completed
    }
}

现在替换switch语句:

DownloadEvent event = getDownloadEvent();
event.doStuff(); // does different stuff depending on the implementing class
相关问题