java反射:建立框架

 

框架的意思就是预先给定一个程序,他可以调用你所给定的程序或任何东西。这样你就可以利用这个框架快速的做一些你想做的事。

反射也能建立框架,比如你可以新建一个配置文件,还有一个预先写好的程序,这样只要在配置文件中修改即可。

我们这里的程序给定了一个config.properties配置文件,这样用户只要在这个配置文件中修改集合的特定类型,即可使用。

  1. import java.io.FileInputStream;  
  2. import java.lang.reflect.Constructor;  
  3. import java.util.Collection;  
  4. import java.util.Iterator;  
  5. import java.util.Properties;  
  6.   
  7. public class ReflectTest {  
  8.   
  9.     public static void main(String[] args) {  
  10.   
  11.         try {  
  12.             FileInputStream fin = new FileInputStream("config.properties");  
  13.             Properties p = new Properties();  
  14.             p.load(fin);  
  15.             String cstr = p.getProperty("collection");  
  16.             Constructor con = Class.forName(cstr).getConstructor(null);  
  17.             Collection col = (Collection) con.newInstance(null);  
  18.             fin.close();  
  19.             ReflectPoint p1 = new ReflectPoint(11);  
  20.             ReflectPoint p2 = new ReflectPoint(22);  
  21.             ReflectPoint p3 = new ReflectPoint(11);  
  22.             ReflectPoint p4 = new ReflectPoint(44);  
  23.             col.add(p1);  
  24.             col.add(p2);  
  25.             col.add(p3);  
  26.             col.add(p4);  
  27.             Iterator i = col.iterator();  
  28.             while(i.hasNext())  
  29.             {  
  30.                 System.out.println(i.next());  
  31.             }  
  32.         } catch (Exception e) {  
  33.             e.printStackTrace();  
  34.         }  
  35.   
  36.     }  
  37.   
  38. }  
  39.   
  40. class ReflectPoint {  
  41.     private int x;  
  42.   
  43.     private int y;  
  44.   
  45.     public ReflectPoint(int x, int y) {  
  46.         super();  
  47.         this.x = x;  
  48.         this.y = y;  
  49.     }  
  50.   
  51.     @Override  
  52.     public int hashCode() {  
  53.         final int prime = 31;  
  54.         int result = 1;  
  55.         result = prime * result + x;  
  56.         result = prime * result + y;  
  57.         return result;  
  58.     }  
  59.   
  60.     @Override  
  61.     public boolean equals(Object obj) {  
  62.         if (this == obj)  
  63.             return true;  
  64.         if (obj == null)  
  65.             return false;  
  66.         if (getClass() != obj.getClass())  
  67.             return false;  
  68.         ReflectPoint other = (ReflectPoint) obj;  
  69.         if (x != other.x)  
  70.             return false;  
  71.         if (y != other.y)  
  72.             return false;  
  73.         return true;  
  74.     }  
  75.   
  76. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值