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;
}
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With