"Javaweb Study notes" 11_xml& reflex

Source: Internet
Author: User
Tags gettext object object

Parsing the XML summary (SAX, pull, Dom three ways)

A brief introduction to reflection:

Reflection

1, what is the reflection technology?

dynamically gets the contents of the specified class and class ( member ) , and run its contents.

The object cannot be used if the application is already running and cannot be created with the new object. You can then find the corresponding bytecode file based on the class name of the configuration file, load it into memory, and create an instance of the class object. This requires the use of reflection technology to complete

2. Three ways to get class objects

Get the Class object one way:

The GetClass method (derived from the object class) that is used by the objects. It is a bit inconvenient to use this class and create an object of that class, and then call the GetClass method to complete.

Person p = new person ();//Create Peron Object

Class clazz = P.getclass ();//The byte-code file object corresponding to person is obtained by means of object Inheritance (GetClass)

Get the class object in two ways:

Each type has a class static property that lets you get the bytecode file object for that class. It's simpler than the first one, and it's done with just a static property. However, it is still a bit inconvenient and must be used in this class.

Class clazz = Person.class;

Get the Class object way three:

* To find out if there is a way to provide access in class?

* found, static Class forname (ClassName);

* Relatively convenient, do not need to directly use the specific class, as long as the name of the class can be known.

* While name completion can be passed as a parameter, this can improve extensibility.

* So in order to get a class dynamically, the third way is most commonly used.

Class Clazz = Class.forName ("Cn.itcast.bean.Person");//Must be full name

How to create a person object

Previously: 1, load Cn.itcast.bean.Person class into memory first.

2, encapsulates the class as a class object.

3, according to the class object, create the Cn.itcast.bean.Person object with the new operator.

4, the constructor is called to initialize the object.

Cn.itcast.bean.Person p = new Cn.itcast.bean.Person ();

By way of three: (also can use constructs, constructs can specify parameters---such as string.class)

String className = "Cn.itcast.bean.Person";

1, gets its corresponding bytecode file object by name

1, by forname () to the specified class name to find the corresponding bytecode file, and loaded into memory.

2, and encapsulates the bytecode file as a class object.

3, complete the creation of the object directly through the Newintstance method.

The 4,newinstance method invocation is the initialization of an empty argument constructor in the class that completes the object.

Class clazz = Class.forName (className);

2, the object creation of the specified class is done through the class method.

Object object = Clazz.newinstance ();//The method is initialized with the completion of the default null argument constructor in the specified class.

Listing 1, gets the fields in the bytecode file.

Class Clazz = class. forname ("Cn.itcast.bean.Person");

Gets the specified field in the class. Like age.

Field field = Clazz.getdeclaredfield ("Age"),//clazz.getfield ("age"); In order to operate on this field, you must first have an object of the specified class.

Object obj = clazz.newinstance ();

For private access, you must remove the access control check for it, using the Setaccessible method in the AccessibleObject parent class

Field.setaccessible (true);//violent access. We recommend that you try not to access private

Field.set (obj, 789);

Gets the value of the field.

Object o = field.get (obj);

System. out. println (o);

Note: Getdeclaredfield: Gets all properties, including private.

GetField: Gets the public property, including inherited from the parent class, excluding the NonPublic method.

Listing 2, gets the method in the bytecode file.

Gets its corresponding bytecode file object by name

Class Clazz = class. forname ("Cn.itcast.bean.Person");

The method of calling a bytecode file object GetMethod gets the public member method of the class represented by the class object (the specified method), the parameter is the method name and the parameters of the current method, no need to create the object, it is a static method

method = Clazz.getmethod ("staticshow", null);

Call the public member method of the class represented by the class object, you need to specify the list of parameters in the object and method

Method.invoke (null, null);

.....................................................................................................................

Class Clazz = class. forname ("Cn.itcast.bean.Person");

Gets the specified method.

method = Clazz.getmethod ("publicshow", null);

Gets the specified class object.

Object obj = clazz.newinstance ();

Method.invoke (obj, null);//The method to which the object is called, is the parameter group

Benefits: Greatly improve the scalability of the program.

Use reflection to complete a method call to an instance object by reading the configuration file

Case one:

public void Testmyservlet () {
try {
1. Creating a Parser Object
Saxreader Saxreader = new Saxreader ();
2. Loading the Web. xml file with the parser to get the Document object
Document document = Saxreader.read ("Src/cn/itheima/web/servlet1/web.xml");
3. Get the root element node
Element rootelement = Document.getrootelement ();
4. Get child element nodes based on element name
Element servletelement = rootelement.element ("servlet");
5. Get the Servlet-class text node based on the element name
String Servletclass = servletelement.element ("Servlet-class"). GetText ();
System.out.println (Servletclass);
6. Get the bytecode file by the full name of the class
Class clazz = Class.forName (Servletclass);
7. Create an Instance Object
MyServlet1 my = (MyServlet1) clazz.newinstance ();
8. Invoke the method inside the instance object
My.init ();
My.service ();
My.destory ();
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

Case TWO:

public class TestMyServlet2 {

8. Create a Map collection

Private hashmap<string, string> data = new hashmap<string,string> ();

@Before

public void Testreadwebxml () {

try {

1. Creating a Parser Object

Saxreader Saxreader = new Saxreader ();

2. Loading the Web. xml file with the parser to get the Document object

Document document = Saxreader.read ("Src/cn/itheima/web/servlet1/web.xml");

3. Get the root element node

Element rootelement = Document.getrootelement ();

4. Get child nodes (Servlets and servlet-mapping)

list<element> childelements = rootelement.elements ();

5. Traverse

for (Element element:childelements) {

6. Determine the element's name as the element node of the servlet

if ("Servlet". Equals (Element.getname ())) {

7. Get the values of Servlet-name and servlet-class for the servlet element node, respectively

String servletname = element.element ("Servlet-name"). GetText ();

String Servletclass = element.element ("Servlet-class"). GetText ();

/*system.out.println (Servletname);

System.out.println (Servletclass); * *

Data.put (Servletname, Servletclass);

}

9. Element node that determines the name of the element as Servlet-mapping

if ("Servlet-mapping". Equals (Element.getname ())) {

10. Get the values of Servlet-name and servlet-class for the servlet element node, respectively

String servletname = element.element ("Servlet-name"). GetText ();

String Urlpattern = element.element ("Url-pattern"). GetText ();

11. Take servletname as key to get the value of Servletclass

String Servletclass = Data.get (servletname);

12. Save the Url-pattern as a key,servletclass as value in the map

Data.put (Urlpattern, Servletclass);

13. Removal of Servletname

Data.remove (Servletname);

}

}

SYSTEM.OUT.PRINTLN (data);

} catch (Documentexception e) {

E.printstacktrace ();

}

}

@Test

public void Testmyservlet () {

try {

1. Simulate entering a URL in the browser

String URL1 = "/myservlet2";

2. Use Urlpattern as key to get Servletclass

String className = Data.get (URL1);

3. Get the bytecode file via Servletclass

Class clazz = Class.forName (className);

4. Creating an instance object from a byte-code file

Object obj = clazz.newinstance ();

5. Get the method through the bytecode file (two parameters: the first is the method name; The second parameter is the parameter of the method)

method = Clazz.getmethod ("service", null);

6. Call the Invoke method to execute the method inside the instance object (method init previously written) "Two parameters: the first is the instance object that invokes the method, and the second is the argument of the method"

Method.invoke (obj, null);

} catch (Exception e) {

E.printstacktrace ();

}

}

}

"Javaweb Study notes" 11_xml& reflex

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.