配置文件Properties集合

特点:主要在序列化的时候使用
   不可以使用泛型
   实现了Map接口(存放的是键值对)
      key和value都是String
作用:作为简单的配置文件使用

通常用于简单工厂模式,一个抽象父类Car ,若干子类Benz BMW ……  ,一个简单工厂CarFactory,一个测试类UI

一个抽象父类Car 

1 public interface Car {
2     public abstract void run();
3 }

一个子类Benz

1 public class Benz implements Car {
2 
3     @Override
4     public void run() {
5         System.out.println("Benz run");
6 
7     }
8 
9 }

一个子类BMW

1 public class BMW implements Car {
2 
3     @Override
4     public void run() {
5         System.out.println("BMW run");
6 
7     }
8 
9 }

一个简单工厂CarFactory

 1 import java.io.FileInputStream;
 2 import java.io.FileNotFoundException;
 3 import java.io.IOException;
 4 import java.util.Properties;
 5 
 6 public class CarFactory {
 7 
 8     public static Car createCar() {
 9         // 通过配置文件来创建车
10         Properties property = new Properties();
11         FileInputStream inStream = null;
12         try {
13             inStream = new FileInputStream("car.properties");
14         } catch (FileNotFoundException e) {
15             System.out.println(e.getMessage());
16 //            e.printStackTrace();
17         }
18         try {
19             property.load(inStream); // 通过流写入集合,获得键值对
20 
21 //            得到Car实现类的全限命名
22             String clazz = property.getProperty("properties");
23 //            使用类反射获取对象实例
24             Class<?> c = Class.forName(clazz);
25             Car car = (Car) c.newInstance();
26             return car;
27         } catch (IOException e) {
28             System.out.println(e.getMessage());
29 //            e.printStackTrace();
30         } catch (ClassNotFoundException e) {
31             System.out.println(e.getMessage());
32 //            e.printStackTrace();
33         } catch (InstantiationException e) {
34             System.out.println(e.getMessage());
35 //            e.printStackTrace();
36         } catch (IllegalAccessException e) {
37             System.out.println(e.getMessage());
38 //            e.printStackTrace();
39         }
40         return null;
41 
42     }
43 }

一个测试Ui 

1 public class CarUi {
2 
3     public static void main(String[] args) {
4         Car car = CarFactory.createCar();
5         car.run();
6     }
7 
8 }

一个car.properties 配置文件,存放了两个类的全限命名

#properties=com.woniu.car.BMW
properties=com.woniu.car.Benz

总结:

配置文件主要的作用是通过修改配置文件可以方便的修改代码中的参数,实现不用改class文件即可灵活变更参数。(想要什么车就改什么车)

解释:java运行中java文件会变成class文件,之后无法通过反编译找到原样的代码,这样的话,如果java类中某个参数变更,就很难灵活的实现参数修改,这个时候properties 文件就能很灵活的实现配置,减少代码的维护成本和提高开发效率。

同样,如果我们存储信息时想要存储在不同的数据库中时,就可以通过修改配置文件来切换数据库(就是键值对,程序中参数是键,全限命名是值,通过修改全限命名我们就可以通过类反射获取到不同的对象,前提是使用多态,许多实现类实现一个接口 Car car = 奔驰或宝马)。

原文地址:https://www.cnblogs.com/19322li/p/10697892.html