-------------------------------------------android培训、期待与您交流 -------------------------------------
Properties类:
java.util.Properties
Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。
load()方法:
原型:public void load(Reader reader)
throws IOException
按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。
getProperty()方法:
原型:public String getProperty(String key)
用指定的键在此属性列表中搜索属性。如果在此属性列表中未找到该键,则接着递归检查默认属性列表及其默认值。如果未找到属性,则此方法返回 null。
参数:
key - 属性键。
返回:
属性列表中具有指定键值的值。
实例运用:
Tip tip = null; try { //使用类反射创建一个类的实例,并转换为(Tip)类型。 tip = (Tip)Class.forName("s2jsp.lg.entity.Tip").newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } tip.setUid(1); tip.setTitle("这是使用类反射机制的"); tip.setContent("这里使用了类反射"); tip.setPublishTime("2002-3-2 17:19:25"); //调用的是实例的getInfo()方法,多态的运用。 tip.getInfo();
"s2jsp.lg.entity.Tip"字符串代表类的名字,必须使用全名。可以是Tip类及其子类,
getInfo()方法为多态实现,其子类也须实现此方法。
可以通过修改字符串,反射回不同的对象(子类),同样实现多态。
newInstance()调用类的无参构造函数。
此字符串可以通过配置文件获得,使用properties类从配置文件读取
例:
Properties prop = new Properties(); try { //自动在bin文件夹中搜寻。 // prop.load(this.getClass().getResourceAsStream("/class.properties")); // 从文件流中装载一个配置文件 prop.load(new FileInputStream( "E:/BBSProject/bin/class.properties")); } catch (IOException e1) { e1.printStackTrace(); } // 获取配置信息 String class_str = prop.getProperty("Tip_class_Name");
class.properties为配置文件名字,新建在src目录中,运行是自动拷贝到bin目录下。
load()从流中加载配置文件。
Tip_class_Name为键名。
Class.properties中的内容为:
Tip_class_Name=s2jsp.lg.entity.Reply
可以在配置中通过修改键的值,改变程序的参数。
public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub //InputStream ips = new FileInputStream("config.properties");//如果使用该方法,则该文件必须放在工程目录下 //InputStream ips = ReflectTest2.class.getClassLoader().getResourceAsStream("cn/itcast/day1/config.properties");在classpath目录中逐一查找该目录,这方法只读 //InputStream ips = ReflectTest2.class.getResourceAsStream("resources/config.properties"); InputStream ips = ReflectTest2.class.getResourceAsStream("/cn/itcast/day1/resources/config.properties"); Properties props = new Properties(); props.load(ips); ips.close(); String className = props.getProperty("className"); Collection collections = (Collection)Class.forName(className).newInstance(); //Collection collections = new HashSet(); ReflectPoint pt1 = new ReflectPoint(3,3); ReflectPoint pt2 = new ReflectPoint(5,5); ReflectPoint pt3 = new ReflectPoint(3,3); collections.add(pt1); collections.add(pt2); collections.add(pt3); collections.add(pt1); //pt1.y = 7; //collections.remove(pt1); System.out.println(collections.size()); }