Using Java reflection to implement Tomcat to add new classes in the run

Source: Internet
Author: User
Tags object object

Personal blog Address: http://www.cnblogs.com/wdfwolf3/. Reproduced in the source, thank you.

Java reflection One is to get the internal structure of the program at run time, and the other is to operate a Java object at runtime. The main uses are the following points:

1. Factory mode:Factory class with reflection, after adding a new class, there is no need to modify the factory class Factory

2. Database JDBC through the Class.forName (Driver) to get the database connection driver

3. Parse the class file: Get the methods in the class and so on , access some inaccessible variables or properties (crack someone else's code).

Before learning some of the reflection of the knowledge, here for the second function to write a small demo, try not to stop the operation of Tomcat (that is, after the Web service startup does not restart the service), the new class into the service, and the ability to successfully load the use. Just to test the reflection, it's easy to build both functionality and the Web. Directly on the source code, not difficult to understand, the following main talk about the operation process.

The project structure is as follows, using Idea+maven+servlet+tomcat

Xml

<?XML version= "1.0" encoding= "UTF-8"?><Web-appXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"ID= "webapp_id"version= "2.4"xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE"xsi:schemalocation= "Http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">    <servlet>        <!--here the name is arbitrary, because the fight into the war package into Tomcat, the access URL path is not related to the name here.  -        <Servlet-name>HttpRequest</Servlet-name>        <!--the implementation class used to specify the servlet -        <Servlet-class>Com.wdf.HttpRequest</Servlet-class>        <Load-on-startup>1</Load-on-startup>    </servlet>    <servlet-mapping>        <!--The name must match the names in the servlet -        <Servlet-name>HttpRequest</Servlet-name>        <!--when calling the Servlet class in the page, the name can be arbitrarily taken, but required/ -        <Url-pattern>/my</Url-pattern>    </servlet-mapping></Web-app>

Dynamicone.java and Dynamictwo.java Two classes are new empty classes and do not need to implement any methods. Httprequest.java inherits classes for HttpServlet, as follows

 PackageCOM.WDF;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportJava.io.*;Importjava.util.ArrayList;Importjava.util.Arrays;Importjava.util.List; Public classHttpRequestextendsHttpServlet {protected voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {Try {            //Classname.txt the name of the class to be loaded, this can also be put in the database test, each query out. Just too lazy to write jdbc. BufferedReader BufferedReader =NewBufferedReader (NewFileReader ("Classname.txt File relative path")); String ClassName=NULL; List<String> list =NewArraylist<>(); //each line of the file has a class name, reads the load by row, and then puts the class name into the list to display.              while((ClassName = Bufferedreader.readline ())! =NULL) {Class C=Class.forName (className); Object Object=c.newinstance ();            List.add (ClassName); } printwriter PrintWriter=Response.getwriter (); Printwriter.println (");            Printwriter.flush ();        Printwriter.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } Catch(ClassNotFoundException e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(instantiationexception e) {e.printstacktrace (); }    }}

Classname.txt store the class name and put it in a local location for the function call.

Com.wdf.reflect.DynamicOnecom.wdf.reflect.DynamicTwo

  That 's what the code is, and then you put the project into a war package through the packages under Maven project, in the Tomcat WebApps directory. It doesn't matter if you don't use Maven or idea, it's a war package. War Package name Reflect.war (the default project name. War). This name is the root path of the URL, which is 127.0.0.1:8080/reflect, then add the Web. XML <servlet-mapping> Set the/my, that's the interview we wrote HttpRequest class. You can see the page showing [Com.wdf.reflect.DynamicOne, Com.wdf.reflect.DynamicTwo], exactly what we expected.
then we create a new Dynamicthree class under the com.wdf.reflect package and build it into a class file, put this file into the webapps/reflect/web-inf/classes /com/wdf/reflect/down, because This is the Tomcat after the start of the parsing war package, the class file after the storage location, put into the correct package location in order to correctly find. Then modify the Classname.txt file to add a lineCom.wdf.reflect.DynamicThree, so that the function can read to this line, get the class name, and then load the dynamicthree.class. After these two steps are completed, refresh the page and see the following to indicate the successful loading.


The entire process does not need to stop Tomcat, using reflection to implement the new class loading. Another function of reflection is to complete the specific use of the loaded class.

Using Java reflection to implement Tomcat to add new classes in the run

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.