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中验证: more rules ...]>
  • 外部dtd文件验证:
  • URL验证:

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




	

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

输出:


最后文件:

Java读取XML实现反射实例_第1张图片








你可能感兴趣的:(Java基础)