[JAVAWEB learning notes] 25_enhanced Foundation: class loaders, annotations @ xxx and dynamic proxies, javaweb @ xxx

Source: Internet
Author: User

[JAVAWEB learning notes] 25_enhanced Foundation: class loaders, annotations @ xxx and dynamic proxies, javaweb @ xxx

Enhanced infrastructure

Learning Objectives

Case-custom unit test @ MyTest

Case study-Solutions to Global Encoding

 

 

I. classloader 1. What is classloader and its role?

The class Loader loads the bytecode file (. class)

 

2. Types of class loaders

There are three classloaders. Different classloaders load different types

 

1) BootStrap: BootStrap loader: loading is the most basic file.

2) ExtClassLoader: extension class loader: loading is a basic file.

3) AppClassLoader: Application Class Loader: third-party jar package and self-compiled java File

 

How to obtain the class loader? (Important)

ClassLoader bytecode object. getClassLoader ();

Public class Demo {public static void main (String [] args) {// Class Loader for obtaining the Demo bytecode File class clazz = Demo. class; // obtain the Demo's bytecode object ClassLoader classLoader = clazz. getClassLoader (); // get the classLoader // The parameter path of getResource is relative to classes (src) // get any resource String path under classes (src) = classLoader. getResource ("com/itheima/classloader/jdbc. properties "). getPath (); // classLoader. getResourceAsStream (""); System. out. println (path );}}

 

 

 

2. annotation @ xxx1. what is annotation?

Annotation is a syntax in a certain format @ xxxx

Annotation function:

Note: Read the program clearly-for the programmer

Note: For jvm, for Machine

 

Annotation is currently the most popular application: replacing the configuration file

Advantages and disadvantages of configuration file and annotation development:

Annotation advantages: high development efficiency and low cost

Annotation disadvantages: High coupling and not conducive to later maintenance

Enterprise trend: hybrid use. Annotations can be used if not frequently modified.

 

2. Annotations provided by JDK 5

@ Override: informs the compiler that this method overwrites the parent class.

@ Deprecated: The annotation is outdated.

@ SuppressWarnings: suppress warning

Deprecation, ignore obsolete

Unused, ignore not to use

Rawtypes, ignore type security

All, ignore all

.....

Problems found:

Different annotations can only be used in different locations (methods, fields, and classes)

 

3. Custom annotation (understanding)

1) how to write a custom Annotation

2) How to Use annotations

3) How to parse annotations ----- use reflection knowledge

 

(1) Compile an annotation

Keyword: @ interface

Annotation attributes:

Syntax: Return Value Name ();

Note: If the attribute name is value and the annotation attribute value has one, the value can be omitted when annotations are used.

Annotation attribute types can only be the following

1. Basic Type

2. String

3. Enumeration type

4. annotation type

5. Class type

6. The preceding types of one-dimensional arrays

(2) Use annotations

@ XXX on the class/method/Field

(3) The annotation class is used for parsing.

Involved in a concept: Meta annotation: represents the annotation of the modified annotation, role: restrict the characteristics of the defined Annotation

@ Retention

SOURCE: The annotation is visible at the SOURCE code level.

CLASS: Annotations are visible at the bytecode file level.

RUNTIME: Annotations are visible throughout the RUNTIME.

@ Target

Represents the scope of annotation modifier: used on the class, used on the method, and used on the field

FIELD: This annotation is available on the FIELD.

METHOD: You can use this annotation on the METHOD.

TYPE: Class/interface can use this Annotation

Note: to parse the class using the annotation, the Retention of the annotation must be set to Runtime.

 

Essence of annotation parsing: parse attribute values from annotations

 

Bytecode objects exist in methods related to obtaining annotations.

IsAnnotationPresent(Class<? extends Annotation> annotationClass) Determines whether the annotation is used on the bytecode object.

GetAnnotation(Class<A> annotationClass): Get the annotation object on the bytecode object

 

4. Case study-custom unit test @ MyTest
Public class MyTestParster {public static void main (String [] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {// obtain TestDemo Class clazz = TestDemo. class; // obtain all methods. Method [] methods = clazz. getMethods (); if (methods! = Null) {// obtain the annotation using the @ MyTest Method for (method: methods) {// determine whether the @ MyTest annotation boolean annotationPresent = Method is used for this method. isAnnotationPresent (MyTest. class); if (annotationPresent) {// This method uses MyTest to annotate the method. invoke (clazz. newInstance (), null );}}}}}

 

3. Dynamic proxy 1. What is proxy (intermediary)

Target object/agent object ------ Homeowner: Real rental Method

Proxy object ------- black intermediary: Method for renting a house (method for calling the house owner's house rental)

The object that executes the proxy object method-the person who rents the house

 

Process: We want to rent a house -----> intermediary (rental method) ------> homeowner (rental method)

Abstract: Call object -----> proxy object ------> target object

2. Dynamic proxy

Dynamic Proxy: you do not need to manually write a proxy object. You do not need to write the same method as the target object one by one. In this process, the proxy object is dynamically generated in the memory of the runtime. ------ Bytecode object-level proxy object

 

Dynamic proxy API:

There is a Proxy in the jdk API that generates a dynamic Proxy method newProxyInstance.

static Object

NewProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)

 

Returned value: the Object is the proxy Object.

Parameter: loader: Class loader with the same object as the target object ------- target object

Like. getClass (). getClassLoader ()

Interfaces: an array of all interface bytecode objects implemented with the target object

H: specific proxy operations, InvocationHandler Interface

 

Note: The dynamic Proxy target object implemented by JDK Proxy must have interfaces and no interfaces. jdk dynamic Proxy cannot be implemented.

 

Example 1:

Public class ProxyTest {@ Test public void test1 () {// obtain a dynamic proxy object ---- create a virtual proxy object for the Target dynamically in the memory at runtime // objProxy is the proxy object and determines the proxy object based on the parameter targetInterface objProxy = (TargetInterface) proxy. newProxyInstance (Target. class. getClassLoader (), // Class Loader with the same object as new Class [] {TargetInterface. class}, new InvocationHandler () {// invoke represents the method for executing the proxy object @ Override // method: representing the method bytecode object of the target object // args: public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {System. out. println ("logic before the target method"); // execute the method Object invoke = method of the target Object. invoke (new Target (), args); System. out. println ("logic after the target method"); return invoke ;}}); objProxy. method1 (); String method2 = objProxy. method2 (); System. out. println (method2 );}}

 

 

Example 2:

Public class ProxyTest2 {public static void main (String [] args) {final Target target = new Target (); // dynamically create a proxy object TargetInterface Proxy = (TargetInterface) proxy. newProxyInstance (target. getClass (). getClassLoader (), target. getClass (). getInterfaces (), new InvocationHandler () {@ Override // how many times are executed? ------- Check the number of times the proxy object calls the method // the corresponding method of the proxy object call interface is to call invoke/** proxy: Is the proxy object * method: it indicates the bytecode Object * args of the target Method: it indicates the parameter */public Object invoke (Object proxy, method Method, Object [] args) when the target method is called) throws Throwable {// reflection knowledge point Object invoke = method. invoke (target, args); // method of the target object // The value returned by retrun to the proxy object return invoke ;}}); proxy. method1 (); // call invoke --- Method: method1 Method of the target object args: null return value null String method2 = proxy. method2 (); // call invoke --- Method: method2 Method of the target object args: null return value method2 int method3 = proxy. method3 (100); // call invoke ----- Method: method3 Method of the target Object args: Object [] {100}. The returned value is 100 System. out. println (method2); System. out. println (method3 );}}

 

 

3. Case study-Solutions to Global Encoding

 

Public class EncodingFilter implements Filter {@ Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {final HttpServletRequest req = (HttpServletRequest) request; // use the dynamic Proxy to complete the global encoding HttpServletRequest enhanceRequset = (HttpServletRequest) Proxy. newProxyInstance (req. getClass (). getClassLoader (), req. getClass (). getInterfaces (), new InvocationHandler () {@ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {// enhance the getParameter method by String name = method. getName (); // obtain the method name of the target object if ("getParameter ". equals (name) {String invoke = (String) method. invoke (req, args); // garbled // transcoding invoke = new String (invoke. getBytes ("iso8859-1"), "UTF-8"); return invoke;} return method. invoke (req, args) ;}}); chain. doFilter (enhanceRequset, response); // request. setCharacterEncoding ("UTF-8"); // enhance the getParameter method of the request before passing the request/*** modifier mode (wrapper) ** 1. The enhancement class and the enhanced class must implement a unified interface * 2. Import the enhanced class in the enhancement class * 3. Rewrite the method to be enhanced without enhancement. call the ** // enhanced object of the reinforced object // HttpServletRequest req = (HttpServletRequest) request; // enhancement object // EnhanceRequest enhanceRequest = new EnhanceRequest (req); // chain. doFilter (enhanceRequest, response) ;}@ Override public void destroy (){}
@ Override public void init (FilterConfig filterConfig) throws ServletException {}} class EnhanceRequest extends detail {private HttpServletRequest request; public EnhanceRequest (HttpServletRequest request) {super (request); this. request = request;} // enhance @ Override public String getParameter (String name) {String parameter = request. getParameter (name); // garbled try {parameter = new String (parameter. getBytes ("iso8859-1"), "UTF-8");} catch (UnsupportedEncodingException e) {e. printStackTrace () ;}return parameter ;}}

 

Related Article

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.