框架的意思就是预先给定一个程序,他可以调用你所给定的程序或任何东西。这样你就可以利用这个框架快速的做一些你想做的事。
反射也能建立框架,比如你可以新建一个配置文件,还有一个预先写好的程序,这样只要在配置文件中修改即可。
我们这里的程序给定了一个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; } }