利用java反射读取xml配置文件

  一、利用java反射机制创建类的实例分为两种情况:

  1、不带参数

复制代码
Class c = Class.forName("className");//返回与带有给定字符串名的类 或接口相关联的 Class 对象。
Object object = c.newInstance();//创建此 Class 对象所表示的类的一个新实例。
System.out.println(object);
复制代码

  2、带参数

复制代码
Class c=Class.forName("className");

Class[] ptype=new Class[]{double.class,int.class};

Constructor constructor=c.getConstructor(ptype);//返回一个 Constructor 对象,它反映此 Class 对象所表示的类的指定公共构造方法

Object[] obj=new Object[]{new Double(3.1415),new Integer(123)};

Object object=construct.newInstance(obt);//使用此 Constructor 对象表示的构造方法来创建该构造方法的声明类的新实例,并用指定的初始化参数初始化该实例。

System.out.println(object);
复制代码

  二、使用dom4j解析xml

需要:dom4j-2.0.0-ALPHA1.jar

下载地址:http://sourceforge.net/projects/dom4j/files/

测试用xml文件

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<package>
    <action name="hello" class="com.flyoung.HelloWorldIml"></action>
</package>
复制代码

使用Dom4j解析xml

复制代码
package com.flyoung;

import org.dom4j.io.SAXReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element; 
import org.dom4j.Attribute;


import java.util.Iterator;
import java.util.List;
import java.io.File; 

public class TestDom4j {
    /**
     * 获取指定xml文档的Document对象,xml文件必须在classpath中可以找到
     *
     * @param xmlFilePath xml文件路径
     * @return Document对象
     */ 
    public static Document parse2Document(String xmlFilePath){
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(new File(xmlFilePath));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return doc;
    }
    
    public static void testParseXmlData(String xmlFilePath){
        //获取xml解析器对象
        //SAXReader reader = new SAXReader();
        //将xml解析为Document对象
        Document doc = TestDom4j.parse2Document(xmlFilePath);
        //获取文档的根元素
        Element root  = doc.getRootElement();
        //定义保存xml数据的缓冲字符串
        StringBuffer sb = new StringBuffer();
        for(Iterator i_action=root.elementIterator();i_action.hasNext();){
            Element e_action = (Element)i_action.next();
            for(Iterator a_action=e_action.attributeIterator();a_action.hasNext();){
                Attribute attribute = (Attribute)a_action.next();
                sb.append(attribute.getName()+":"+attribute.getValue());
                sb.append("\n");
            }
        }
        System.out.println(sb);
        
    }
    public static void main(String[] args) {
        TestDom4j.testParseXmlData("E:/workspace/Dom4j/test.xml");

    }
}
复制代码

输出结果

复制代码
name:hello
class:com.flyoung.HelloWorldIml
复制代码

参考:http://xhy0422.iteye.com/blog/50235

  三、使用java发射机制创建类的实例

业务接口

复制代码
package com.flyoung;

public interface HelloWorld {
    public void sayHelloWorld();
}
复制代码

业务接口实现

复制代码
package com.flyoung;

public class HelloWorldIml implements HelloWorld {

    public void sayHelloWorld() {
        System.out.println("Hello World!!!");

    }

}
复制代码

读取xml配置文件创建类的实例

复制代码
package com.flyoung;

import org.dom4j.io.SAXReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element; 
import org.dom4j.Attribute;


import java.util.Iterator;
import java.util.List;
import java.io.File; 
import java.util.Map;
import java.util.HashMap;

public class TestDom4j {
    /**
     * 获取指定xml文档的Document对象,xml文件必须在classpath中可以找到
     *
     * @param xmlFilePath xml文件路径
     * @return Document对象
     */ 
    public static Document parse2Document(String xmlFilePath){
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(new File(xmlFilePath));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return doc;
    }
    
    public static Map testParseXmlData(String xmlFilePath){
        //获取xml解析器对象
        //SAXReader reader = new SAXReader();
        //将xml解析为Document对象
        Document doc = TestDom4j.parse2Document(xmlFilePath);
        //获取文档的根元素
        Element root  = doc.getRootElement();
        //定义保存xml数据的缓冲字符串
        //StringBuffer sb = new StringBuffer();
        //定义保存属性、值的map
        Map<String,String> map = new HashMap<String,String>();
        for(Iterator i_action=root.elementIterator();i_action.hasNext();){
            Element e_action = (Element)i_action.next();
            for(Iterator a_action=e_action.attributeIterator();a_action.hasNext();){
                Attribute attribute = (Attribute)a_action.next();
                //sb.append(attribute.getName()+":"+attribute.getValue());
                //sb.append("\n");
                map.put(attribute.getName(), attribute.getValue());
            }
        }
        //System.out.println(sb);
        return map;
        
    }
    public static void main(String[] args) {
        Map map = TestDom4j.testParseXmlData("E:/workspace/Dom4j/test.xml");
        String className =(String)map.get("class");
        try {
            Class c = Class.forName(className);
            HelloWorld hw =(HelloWorld) c.newInstance();
            hw.sayHelloWorld();    
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {    
            e.printStackTrace();
        }
    }

}
复制代码

输出结果

复制代码
Hello World!!!
复制代码

此文是为利用动态代理实现简单的aop作铺垫。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值