通过修改配置文件,可直接得到不同的配置对象信息
2011年08月01日
package com.potevio.zjx.study; public class Car implements Moveable { public void run() { System.out.println("Audi奔驰在宽阔的马路上..."); } } package com.potevio.zjx.study; public interface Moveable { void run(); } package com.potevio.zjx.study; public class Train implements Moveable { public void run() { System.out.println("一辆火车正缓缓驶入北京西站..."); } } //VehicleType=com.potevio.zjx.study.Car VehicleType=com.potevio.zjx.study.Trainpackage com.potevio.zjx.study; import java.util.Properties; public class Test { public static void main(String[] args) throws Exception { Properties props = new Properties(); props.load(Test.class.getClassLoader() .getResourceAsStream("com/potevio/zjx/study/study_ pro.properties")); String vehicleTypeName = props.getProperty("VehicleType"); System.out.println("vehicle:"+vehicleTypeName); Object o = Class.forName(vehicleTypeName).newInstance(); Moveable m = (Moveable)o; m.run(); } }
通过修改配置文件,可直接得到不同的配置对象信息
Notice:这些文件在同一个包下
2011年08月01日
package com.potevio.zjx.study; public class Car implements Moveable { public void run() { System.out.println("Audi奔驰在宽阔的马路上..."); } } package com.potevio.zjx.study; public interface Moveable { void run(); } package com.potevio.zjx.study; public class Train implements Moveable { public void run() { System.out.println("一辆火车正缓缓驶入北京西站..."); } } //VehicleType=com.potevio.zjx.study.Car VehicleType=com.potevio.zjx.study.Trainpackage com.potevio.zjx.study; import java.util.Properties; public class Test { public static void main(String[] args) throws Exception { Properties props = new Properties(); props.load(Test.class.getClassLoader() .getResourceAsStream("com/potevio/zjx/study/study_ pro.properties")); String vehicleTypeName = props.getProperty("VehicleType"); System.out.println("vehicle:"+vehicleTypeName); Object o = Class.forName(vehicleTypeName).newInstance(); Moveable m = (Moveable)o; m.run(); } }
通过修改配置文件,可直接得到不同的配置对象信息
Notice:这些文件在同一个包下
本文介绍了一种利用配置文件来动态选择并实例化不同Java类的方法。通过加载配置文件中的类名,程序可以运行时决定创建哪个类的对象,并调用其方法。这种方法提高了系统的灵活性和可扩展性。

被折叠的 条评论
为什么被折叠?



