Java读取XML实现反射实例

* XML(Extensible Markup Language,可扩展标记语言)

1、XML DOM解析:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File f = ...
Document doc=builder.parse(f);
URL u=...
Document doc=builder.parse(u);
InputStream in=...
Document doc=builder.parse(in);

2、XML DTD(Document Type Definition,文档类型验证)验证:

  • XML中验证:<!DOCTYPE configuration [<!Element configuration ...> more rules ...]>
  • 外部dtd文件验证:<!DOCTYPE configuration SYSTEM "config.dtd">
  • URL验证:<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">

3、XML Schema:其本身就是一个XML文件,同时其内容指明了某种XML的格式。

关于dtd和XML Schema文档的编写可以参考《Java核心技术 卷II》Page 152-154中给出的具体文件内容示例。

本文参考 https://blog.csdn.net/bjhecwq/article/details/5872960 中的相关程序!

有关XML文件的介绍可以参阅 https://blog.csdn.net/zoeban/article/details/8617597

实例主要逻辑:

  • HelloWorld.java提供反射机制访问的类
  • test.xml文件给出HelloWorld类的信息
  • Test.java文件读取xml中的类信息,并利用反射机制生成HelloWorld类的实例,并调用其中的方法

具体文件如图所示


各文件内容如下

HelloWorld.java

import java.util.Arrays;

public class HelloWorld {

	public void sayHello(){
		System.out.println("sya hello");
	}
  
	public void sayHello(int i){
		System.out.println("sya hello: " + i);
	}

	public void sayHello(String[] str){
		System.out.println("say hello: " + Arrays.toString(str));
	}

	public static void main(String[] args) {
		String[] str = {"a", "b"};
		HelloWorld h = new HelloWorld();
		h.sayHello(str);
		System.out.println("hello world");
	}
}

test.xml

<?xml version="1.0" encoding="UTF-8"?>

<element>
	<import class="HelloWorld"/>
</element>

Test.java

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Test {
  /**
   * @param args
   * @throws IOException
   * @throws ParserConfigurationException 
   * @throws SAXException 
   * @throws ClassNotFoundException 
   * @input
   */
  public static void main(String[] args) throws Exception, ParserConfigurationException, SAXException, ClassNotFoundException {
    DocumentBuilder builder;
    builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    if (args.length == 0)
      return;
    else {
      InputStream in=null;
      try {
		//读取XML文件
        String filePath = args[0];
        File file = new File(filePath);
        in = new FileInputStream(file);
        Document doc=builder.parse(in);
        Element eRoot = doc.getDocumentElement();
        NodeList nl = eRoot.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
          Node n = nl.item(i);
          if (!(n instanceof Element))
            continue;
          Element e = (Element) n;
          System.out.println("Element: " + e.getNodeName());
		  //取得类名
          String className=e.getAttribute("class");
          Class cl=Class.forName(className);
		  //创建类实例对象
          Object o=cl.newInstance();
		  //动态调用方法
          Method m=cl.getMethod("sayHello",  String[].class);
          Object[] ob=new Object[1];
          String arg[]=new String[1];
          arg[0]="1";
          ob[0]=arg;
          m.invoke(o,ob);
        }
      } 
	  finally {
        in.close();
      }
    }
  }
}

具体运行方法:

  1. javac HelloWorld.java
  2. javac -encoding utf-8 Test.java
  3. java Test test.xml

输出:


最后文件:









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值