一个用XML配置的动态加载办法,比上一个全面,希望还能进精华区

80酷酷网    80kuku.com

  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文件方式比好象慢一些,郁闷~



分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: