package com.wkcto.chapter08.demo03;
import java.io.IOException;
import java.io.InputStream;
/**
* 定義一個(gè)業(yè)務(wù)邏輯類(lèi)
* 需要使用Collection集合
* @author 蛙課網(wǎng)
*
*/
import java.util.Collection;
import java.util.Properties;
public class DataOP {
static Collection collection; //定義Collection引用
static{
/*
* 靜態(tài)代碼塊, 在類(lèi)加載內(nèi)存后,在類(lèi)使用前執(zhí)行,
* 有時(shí), 這個(gè)類(lèi)需要依賴一些外部資源, 就可以在靜態(tài)代碼塊中加載這些依賴資源
* 在本例中, 可以在靜態(tài)代碼塊中從配置文件中讀取Collection集合的實(shí)現(xiàn)類(lèi)名
*/
try {
Properties properties = new Properties();
InputStream inStream = DataOP.class.getResourceAsStream("/com/wkcto/chapter08/demo03/config.properties");
properties.load(inStream);
String className = properties.getProperty("classname");
//通過(guò)反射技術(shù) 創(chuàng)建實(shí)例
Class<?> class1 = Class.forName(className);
collection = (Collection) class1.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException e) {
e.printStackTrace();
}
}
//把數(shù)據(jù)添加到集合中
public void addData() {
collection.add("data11");
}
//顯示數(shù)據(jù)
public void show() {
System.out.println( collection );
}
}
在當(dāng)前包中添加config.properties配置文件,
classname=java.util.HashSet