java反射小例子

[html] view plain copy
 print?
  1. package reflect;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.util.Properties;  
  9.   
  10. interface fruit{  
  11.     public abstract void eat() ;  
  12. }  
  13. class Apple implements fruit{  
  14.   
  15.     public void eat() {  
  16.         System.out.println("eat Apple");  
  17.     }  
  18.       
  19. }  
  20. class orange implements fruit{  
  21.   
  22.     public void eat() {  
  23.         System.out.println("eat orange");  
  24.     }  
  25.       
  26. }  
  27. class init{  
  28.     public static Properties getPro() throws FileNotFoundException, IOException{  
  29.         Properties pro = new Properties() ;  
  30.         File f = new File("fruit.properties") ;  
  31.         if(f.exists()){  
  32.             System.out.println("有配置文件!");  
  33.             //从配置文件中读取键值对  
  34.             pro.load(new FileInputStream(f)) ;  
  35.         }else{  
  36.             System.out.println("没有配置文件!");  
  37.             pro.setProperty("apple", "reflect.Apple") ;  
  38.             pro.setProperty("orange", "reflect.orange") ;  
  39.             pro.store(new FileOutputStream(f), "FRUIT CLASS") ;  
  40.         }  
  41.         return pro ;  
  42.     }  
  43. }  
  44. class Factory{  
  45.     public static fruit getInstance(String className){  
  46.         fruit f = null ;  
  47.         try {  
  48.             //通过反射得到fruit的实例对象  
  49.             f = (fruit)Class.forName(className).newInstance() ;  
  50.         } catch (InstantiationException e) {  
  51.             e.printStackTrace();  
  52.         } catch (IllegalAccessException e) {  
  53.             e.printStackTrace();  
  54.         } catch (ClassNotFoundException e) {  
  55.             e.printStackTrace();  
  56.         }  
  57.         return f ;  
  58.     }  
  59. }  
  60. public class Hello {  
  61.     public static void main(String[] args) {  
  62.         try {  
  63.             Properties pro = init.getPro() ;  
  64.             fruit f = Factory.getInstance(pro.getProperty("apple")) ;  
  65.             if(f != null){  
  66.                 f.eat() ;  
  67.             }  
  68.         } catch (FileNotFoundException e) {  
  69.             // TODO Auto-generated catch block  
  70.             e.printStackTrace();  
  71.         } catch (IOException e) {  
  72.             // TODO Auto-generated catch block  
  73.             e.printStackTrace();  
  74.         }  
  75.           
  76.     }  
  77. }  

java反射小例子

结果为:

有配置文件!
eat Apple