wangqinqin 发表于 2013-2-3 10:38:26

java中的反射Reflection应用之三

package day11.javaAdvance.exercise.reflection.Class;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;import java.util.Properties;public class ClassTest4 {public static void main(String[] args) {Biz1 b = new Biz1();b.finteat();}}class Biz1 {Animal animal = (Animal) AnimalFactory.getObject("impl");public void finteat() {animal.eat();}}class AnimalFactory {static Properties pro = new Properties();static {try {pro.load(new FileInputStream("config2.properties"));// 文件放在根目录下} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static Object getObject(String name) {Object obj = null;String className = pro.getProperty(name);// name即是key键值,className即是value值。try {Class c = Class.forName(className);Class[] cl = {};Constructor con = c.getDeclaredConstructor(cl);Object[] obj1 = {};obj = con.newInstance(obj1);System.out.println("类全名是:" + obj);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return obj;}}interface Animal1 {public void eat();}class Dog1 implements Animal {public void eat() {System.out.println("dog eatting ....");}}class Cat1 implements Animal {public void eat() {System.out.println("cat eatting....");}} 其中的配置文件在config2.properties文件中。
配置文件中是键值对,其中的key=impl,value分别是Dog1类和Cat1类,以类全名方式赋值。其内容是:
impl= day11.javaAdvance.exercise.reflection.Class.Dog1
#impl=day11.javaAdvance.exercise.reflection.Class.Cat1
这样我们只要传递键值,即可得到配置文件中的value值即是代码中的:String className = pro.getProperty(name);得到的className即是value值。
使用配置文件的好处:不需在源代码中去修改代码,只需在配置文件中修改,这样很好体现了java的封装性这一特点。
 
 
页: [1]
查看完整版本: java中的反射Reflection应用之三