用java读取Properties文件来改变实现类的Demo:public abstract class Vehicle {public abstract void run();}public class Car extends Vehicle{public void run(){System.out.println("with Car");}}public class Broom extends Vehicle {@Overridepublic void run() {System.out.println("Broom");}}test.properties 中:VehicleType=abstractfactory.step4properties.Broom注意:该文件要放在src目录下,且等号两边不可有空格import java.util.Properties;public class Test {public static void main(String[] args) throws Exception{Properties pros = new Properties();///配置文件编译之后放在bin目录下//每个class的类,都会被当作Class对象。getClassLoader:拿到了装载这个Class的装载器///把它当作一个流读进来,默认路径是根目录。读出来之后,把它转化为一个properties对象,然后,等号左边的就是key,等号右边的就是valuepros.load(Test.class.getClassLoader().getResourceAsStream("abstractfactory/step4properties/spring.properties"));String vehicleTypeName = pros.getProperty("VehicleType");System.out.println(vehicleTypeName);///现在,得到的字符串,我们想把字符串代表的类,产生一个对象,用到反射///Class.forName把字符串所代表的表装到内存,newInstance:生成对象,得到的是个ObjectVehicle v = (Vehicle)Class.forName(vehicleTypeName).newInstance();v.run();//只要改变test.properties中的VehicleType=factory.step4Spring.Broom,即可实现改变实现类的功能。}}
(转载请注明出处:[url=http://www.k6567.com]e世博[/url][url=http://www.d9732.com]澳门博彩[/url])