反射技术大量用于Java设计模式和框架技术,最常见的设计模式就是工厂模式(Factory)和单例模式(Singleton)。
参考URL:
http://blog.csdn.net/xiaohai798/article/details/11640427
用接口来沟通不同程序的开发进度,不必等上游程序写好代码之后,再注入后面流程的程序员。且在实现上,可以用配置文件灵活变更,而不用重编译整个项目。
InterfaceTest.java:
interface InterfaceTest {
//基于接口规范 public void getName(); }
Test1.java:
class Test1 implements InterfaceTest {
//不同程序员可以实现不同的重写功能 public void getName() { System.out.println("test1"); } }
Test2.java:
class Test2 implements InterfaceTest { public void getName() { System.out.println("test2"); } }
Factory.java:
import java.io.FileInputStream; import java.util.Properties; class Factory { private static Properties pro = new Properties(); static { try {
//通过配置文件来实现载入不同的类,实现不同的功能 pro.load(new FileInputStream("file.txt")); } catch (Exception e) { e.printStackTrace(); } } //保证单例 private static Factory factory = new Factory(); private Factory() {} public static Factory getFactory() { return factory; } public InterfaceTest getInstance() { InterfaceTest interfaceTest = null; try {
//反映功能可灵活实例化不同的类,作框架是很灵活自由的啦 String classInfo = pro.getProperty("test"); Class c = Class.forName(classInfo); Object obj = c.newInstance(); interfaceTest = (InterfaceTest)obj; } catch (Exception e) { e.printStackTrace(); } return interfaceTest; } }
FactoryTest.java:
public class FactoryTest { public static void main(String[] args) { System.out.println("~~~~~~~~~~~~~~~~"); Factory factory = Factory.getFactory(); System.out.println("!!!!!!!!!!!!!!!!!"); InterfaceTest inter = factory.getInstance(); System.out.println("@@@@@@@@@@@@@@@@@@"); inter.getName(); System.out.println("##################"); } }