📄 configtest.java
字号:
package lianxi;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.lang.reflect.*;
import java.util.*;
import org.com.gather.*;
public class ConfigTest{
private Properties pro = null;
private static String key = "abc";
private Document doc = null;
private static ConfigTest instance = null;
private ConfigTest(Properties pro){
this.pro = pro;
}
public static ConfigTest getInstance(Properties pro){
if(instance == null){
synchronized(key){
if(instance == null){
instance = new ConfigTest(pro);
instance.init(pro.getProperty("xmlPath"));
}
}
}
return instance;
}
public void init(String xmlPath){
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(xmlPath);
}catch(Exception e){
e.printStackTrace();
}
}
public DB getDB(){
return (DB)loadClass("db");
}
public Object loadClass(String nodeName){
Properties pro = getNodeProperties("db");
String single = pro.getProperty("single");
String methodName = pro.getProperty("methodName");
if(single.equals("true")){
return ClassLoaderFactory.loadClassByMethod(methodName,pro);
}else{
return ClassLoaderFactory.loadClassByConstructor(pro);
}
}
public Properties getNodeProperties(String nodeName){
Properties pro = new Properties();
Node fatherNode = doc.getElementsByTagName(nodeName).item(0);
NamedNodeMap attributes = fatherNode.getAttributes();
for(int i = 0; i < attributes.getLength(); i++){
Node an = attributes.item(i);
String attribute_name = an.getNodeName();
String attribute_value = an.getNodeValue();
pro.setProperty(attribute_name,attribute_value);
}
NodeList childList = fatherNode.getChildNodes();
for(int i = 0; i < childList.getLength(); i++){
Node cn = childList.item(i);
if(cn instanceof Element){
String childNodeName = cn.getNodeName();
String childNodeValue = cn.getFirstChild().getNodeValue();
pro.setProperty(childNodeName,childNodeValue);
}
}
System.out.println("Properties is <--->"+pro);
return pro;
}
}
class ClassLoaderFactory{
public static Object loadClassByMethod(String methodName,Properties pro){
try{
ClassLoader cl = ClassLoader.getSystemClassLoader();
String className = pro.getProperty("className");
Class c = cl.loadClass(className);
Method method = c.getMethod(methodName,new Class[]{Properties.class});
return method.invoke(c,new Object[]{pro});
}catch(Exception e){
e.printStackTrace();
return null;
}
}
public static Object loadClassByConstructor(Properties pro){
try{
ClassLoader cl = ClassLoader.getSystemClassLoader();
String className = pro.getProperty("className");
Class c = cl.loadClass(className);
Constructor ct = c.getConstructor(new Class[]{Properties.class});
return ct.newInstance(new Object[]{pro});
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -