I have the following code and I'm wondering if there is a way to use a switch block instead of a bunch of if/else statements. I know that Java supports strings in switch blocks as of Java 1.7 but I'm still working with Java 1.6:
} else if (typeName.equals("Boolean")) {
return new SwitchInputType<Boolean>(new Boolean((String) memberValue));
} else if (typeName.equals("Double")) {
return new SwitchInputType<Double>(new Double((String) memberValue));
} else if (typeName.equals("Int32"))
Yes, we can use a switch statement with Strings in Java.
switch expression can't be float, double or boolean.
A switch works with the byte , short , char , and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character , Byte , Short , and Integer (discussed in Numbers and Strings).
The switch statement or switch case in java is a multi-way branch statement. Based on the value of the expression given, different parts of code can be executed quickly. The given expression can be of a primitive data type such as int, char, short, byte, and char.
You could even make the enum
do it for you:
public static void main(String[] args) throws InterruptedException {
String typeName = "Boolean";
String memberValue = "memberValue";
SwitchInputType type = Type.valueOf(typeName).makeType(memberValue);
}
enum Type {
Boolean {
SwitchInputType makeType(String memberValue) {
return new SwitchInputType<Boolean>(new Boolean(memberValue));
}
},
Double {
SwitchInputType makeType(String memberValue) {
return new SwitchInputType<Double>(new Double(memberValue));
}
},
Int32 {
SwitchInputType makeType(String memberValue) {
return new SwitchInputType<Integer>(new Integer(memberValue));
}
};
// All must do this.
abstract SwitchInputType makeType(String memberValue);
}
static class SwitchInputType<T> {
public SwitchInputType(Object o) {
}
}
As your strings are all valid identifiers, you could create an enumeration with those strings as the item labels, use Enum.valueOf(Class, String) (or the similar valueOf(String)
method that will be created in your enumeration class) to convert to a member of the enumeration type, and then switch based on that...
Example:
enum TypeName { Boolean, Double, Int32 }
switch (TypeName.valueOf(typeName)) {
case Boolean: // ...
case Double: // ...
case Int32: // ...
}
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