一個用XML配置的動態載入辦法,比上一個全面,希望還能進精華區
來源:互聯網
上載者:User
xml|動態|載入|精華 首先設計一個簡單的XML設定檔config.xml
<?xml version='1.0' encoding='utf-8'?>
<test>
<luck title="Luck Bang Bang Bang" tag="LUCK" application="dispatch.test" method="mm">
</luck>
</test>
接下來一個分析XML的方法,用到JAXP,dispatch.java
package dispatch;
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
public class dispatch extends DefaultHandler
{
//public dispatch(){
public void execute(){
DefaultHandler handler = new dispatch();
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new File("dispatch/config.xml"),handler);
} catch (Throwable t) {
t.printStackTrace();
}
}
dynamicLoader loader = new dynamicLoader();
//===========================================================
// SAX DocumentHandler methods
//===========================================================
public void startElement(String namespaceURI,
String lName, // local name
String qName, // qualified name
Attributes attrs)
throws SAXException
{
//DEBUG//
String ftag = "LUCK";
////////
String eName = lName; // element name
if ("".equals(eName)) eName = qName; // namespaceAware = false
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
if(ftag.equals(attrs.getValue(i))){
System.out.println(loader.loader(attrs.getValue(i+1),attrs.getValue(i+2),"See it ??"));
break;
}//if equals
}//for i
}//if !null
}
public static void main(String argv[]){
dispatch get = new dispatch();
get.execute();
}
}
再來一個動態載入方法dynamicLoader.java
package dispatch;
import java.lang.*;
import java.lang.reflect.*;
public class dynamicLoader{
public dynamicLoader(){
}
public String loader(String appName,String mthName,String ctn){
String reStr = "";
Class toRun = null;
try{
toRun = Class.forName(appName);
Method fToGo = toRun.getDeclaredMethod(mthName,new Class[]{String.class});
reStr = fToGo.invoke(toRun.newInstance(),new Object[]{ctn}).toString();
}catch(Exception e){
System.out.println("loader:"+e+"|"+mthName+"|"+appName+"|"+ctn);
}
return reStr;
}
}
一個小小的調試指令碼,只是用來返回參數test.java
package dispatch;
public class test{
public String mm(String str){
return str;
}
}
XML檔案的分析需要系統加JAXP、JAXR、JAXM、JAXRPC,具體的去看SAX的文檔我這裡就不贅述了。
這個聯起來可以跑了,只是速度太慢,跟同事用同樣原理的.propertier檔案方式比好象慢一些,鬱悶~