Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Switchable class in Java

I want to create a switchable class in java A one that I can make switch case on it something like that

public class MySwitchableClass implements Comparable<MySwitchableClass>
{
    @Override
    public int compareTo(MySwitchableClass arg0) {
    // TODO Auto-generated method stub
    return 0;
    }
}

and then I use it like that

    MySwitchableClass s = new MySwitchableClass();
    MySwitchableClass s1 = new MySwitchableClass();

    switch(s){
    case s1:
        //do something
        break;
        default break;
    }
like image 758
Isyola Avatar asked Sep 26 '13 09:09

Isyola


2 Answers

Not possible. From JLS :

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.

like image 69
Arnaud Denoyelle Avatar answered Oct 05 '22 03:10

Arnaud Denoyelle


The switch statement does not accept classes, but it does accept enums. You can create an enum type to hold the class types and set them as a field in each class. The enum type can then be exposed through an interface method, which is utilized in the switch statement.

MyClassType Enum

public enum MyClassType {
    CLASSA, CLASSB
}

Discoverable Interface

public interface Discoverable {
    public MyClassType getType();
} 

ClassA

public class ClassA implements Discoverable {

    private MyClassType type = MyClassType.CLASSA;

    public MyClassType getType() {
        return type;
    }

}

ClassB

public class ClassB implements Discoverable {

    private MyClassType type = MyClassType.CLASSB;


    public MyClassType getType() {
        return this.type;
    }
}

Usage

public static void main(String[] args) {
    Discoverable a = new ClassA();
    Discoverable b = new ClassB();

    switch (a.getType()) {
    case CLASSA:
        System.out.println("class a");
        break;
    case CLASSB:
        System.out.println("class b");
        break;
    }

}

An even better approach would be to put this logic into ClassA and ClassB and expose it through the interface.

Interface Changes

public interface Discoverable {
    public void doWork();

}

ClassA Changes

public class ClassA implements Discoverable {

    public void doWork() {
        System.out.println("class a");
    }
}

ClassB

public class ClassB implements Discoverable {

    public void doWork() {
        System.out.println("class b");
    }
}

Usage

public static void main(String[] args) {
    Discoverable a = new ClassA();
    Discoverable b = new ClassB();
    a.doWork();    
} 
like image 30
Kevin Bowersox Avatar answered Oct 05 '22 03:10

Kevin Bowersox