//這個 TestZoo.java 是要 demo Class.forname(String) 的妙用 //@CopyLeft by tsaiwn@csie.nctu.edu.tw public class TestZoo { static String s1="Dog", s2="Cat", s3="People", s4="Dog"; public static void main(String x[]) throws Exception { for(int i=1; i<= 4; i++){ String s = s3; // assume default is people if(i==1) s=s1; else if(i==2) s=s2; else if(i==3)s=s4; try{ Object o=Class.forName(s).newInstance(); System.out.println("shows up."); }catch(Exception e) { System.out.println("GOGO"); } }System.out.println(); } } // class TestZoo class Dog{ Dog(){ System.out.print("汪汪旺 ");} } class Cat{ Cat(){ System.out.print("Miao ");} } //Don't take life too seriously -- you'll never get out if it alive.