-
什么是反射
反射java语言中的一种机制,通过这种机制可以动态的实例化对象、读写属性、调用方法 -
java.lang.Class 类对象 特定类
-
一切反射相关的代码都从获得类对象开始 == 实例化对象
3.1 Class.forName(完整类名又称全限定类名)
3.2 类名.class
3.3 对象.getClass()
4.读写属性
例题
public static void main(String[] args) throws IOException, DocumentException {
// TODO Auto-generated method stub
/*
InputStream in=Demo1.class.getResourceAsStream("db.properties"); //实例化对象
Properties p=new Properties();
p.load(in);
System.out.println(p.getProperty("upass"));
*/
InputStream in=Demo1.class.getResourceAsStream("students.xml");
SAXReader sr=new SAXReader();
Document doc=sr.read(in);
//单个获取
// System.out.println(doc.asXML());
// List<Element> selectN=doc.selectNodes("/students/student");
// for (Element e : selectN) {
// System.out.println(e.asXML());
// }
Element stuEle=(Element)doc.selectSingleNode("/students/student[@sid='s001']");
// System.out.println(stuEle.asXML());
// System.out.println(stuEle.attributeValue("sid"));
System.out.println(((Element)stuEle.selectSingleNode("name")).asXML());//这里需要强转
}
ServletContext sc=this.getServletContext();
InputStream is= sc.getResourceAsStream("/WEB-INF/config.xml");
SAXReader sr=new SAXReader();
Document doc=null;
try {
doc=sr.read(is);
// 1、获取所有action中的type的值
// List<Element> conEles= doc.selectNodes("/config/action");
// for (Element element : conEles) {
// System.out.println(element.attributeValue("type"));
// }
// 2、获取第二个action中的type的值
// Element conSingle= (Element) doc.selectSingleNode("/config/action[@path='/loginAction']");
// System.out.println("第二个action中的type的值:"+conSingle.attributeValue("type"));
// 3、获取第二个action的所有forward的path
// Element conSingle= (Element) doc.selectSingleNode("/config/action[@path='/loginAction']");
// List<Element> conEles = conSingle.selectNodes("forward");
// for (Element e : conEles) {
// System.out.println("第二个action的所有forward的path:"+e.attributeValue("path"));
// }
// 4、获取第二个action的第二个forward的path
Element conSingle1= (Element) doc.selectSingleNode("/config/action[@path='/loginAction']");
Element conSingle2 = (Element) conSingle1.selectSingleNode("forward[@name='success']");
System.out.println("第二个action的第二个forward的path:"+conSingle2.attributeValue("path"));
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
web.Xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>conServlet</servlet-name>
<servlet-class>com.zking.xmlParse.ConfigServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>conServlet</servlet-name>
<url-pattern>/ConfigServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>aa</servlet-name>
<servlet-class>abcdefg</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>aa</servlet-name>
<url-pattern>/hh</url-pattern>
</servlet-mapping>
</web-app>