java反射:建立框架

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

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

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

import java.io.FileInputStream; import java.lang.reflect.Constructor; import java.util.Collection; import java.util.Iterator; import java.util.Properties; public class ReflectTest { public static void main(String[] args) { try { FileInputStream fin = new FileInputStream("config.properties"); Properties p = new Properties(); p.load(fin); String cstr = p.getProperty("collection"); Constructor con = Class.forName(cstr).getConstructor(null); Collection col = (Collection) con.newInstance(null); fin.close(); ReflectPoint p1 = new ReflectPoint(1, 1); ReflectPoint p2 = new ReflectPoint(2, 2); ReflectPoint p3 = new ReflectPoint(1, 1); ReflectPoint p4 = new ReflectPoint(4, 4); col.add(p1); col.add(p2); col.add(p3); col.add(p4); Iterator i = col.iterator(); while(i.hasNext()) { System.out.println(i.next()); } } catch (Exception e) { e.printStackTrace(); } } } class ReflectPoint { private int x; private int y; public ReflectPoint(int x, int y) { super(); this.x = x; this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ReflectPoint other = (ReflectPoint) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值