java1.7已经支持了匹配字符串
方案1.
enum Animal { dog,cat,bear; public static Animal getAnimal(String animal){ return valueOf(animal ); } } public class Client { public void caseAnimal(String animal){ switch(Animal.getAnimal(animal)){ case cat: System.out.println("this is a cat"); break; case dog: System.out.println("this is a dog"); break; case bear: System.out.println("this is a bear"); break; } } public static void main(String[] args) { Client client = new Client(); client.caseAnimal("cat"); } }
方案2
enum Seasons{ SPRING,SUMMER,AUTUMN,WINTER } public class TestMultiInterface{ public static void main(String[] args){ Seasons str=Seasons.SPRING; switch(str.ordinal()){ case 0: System.out.println(str.toString()); break; case 1: System.out.println(str.toString()); break; default: System.out.println("没找到"); } } }
方案3
public void switchCase() { Map<String,Integer> map=new HashMap<String, Integer>(); map.put("中国", 1); map.put("美国", 2); map.put("英国", 3); map.put("法国", 4); String str="中国"; switch(map.get(str)) { case 1: System.out.println("中国"); break; case 2: System.out.println("美国"); break; case 3: System.out.println("英国"); break; case 4: System.out.println("法国"); break; default: System.out.println("default"); } }
方案4
String str1 = "aa"; String[] str2 = {"bb", "aa", "cc", "aaa"}; for (int i = 0; i < str2.length; ++i){ switch (str1.compareTo(str2[i])) { case 0: System.out.println("OK"); break; default: System.out.println("Error"); break; } }
方案5
public class Client { public Client(String animal) { //使用String的hasCode取得字符串的哈希码,此方法要保证哈希码不重复 switch (animal.hashCode()) { case 98262: System.out.println("this is a cat"); break; case 99644: System.out.println("this is a dog"); break; case 3019700: System.out.println("this is a bear"); break; } } public static void main(String[] args) { Client client = new Client("bear"); }
方案6 如果是在使用简单工厂设计模式,可以考虑利用java反射技术代替switch
public static UserDao createUser(){
Animal animal=null;
try {
iu=(Animal) Class.forName(Animal接口下子类的完整类名).newInstance();
}catch (Exception e) {
e.printStackTrace();
}
return animal; }
以上方案,有的是从网上收集来的,有的是自己原创的,因为时间过长,已经不记得从哪个地方摘抄下来的,没有注明转载的地方,十分抱歉!