"Javaweb Learning Notes" 25_ Foundation enhancement: classloader, annotations @xxx, and dynamic proxies

Source: Internet
Author: User
Tags throwable

Foundation strengthening

Learning Goals

Case-Custom Unit test @mytest

Case-resolution of the global encoding

First, class loader 1. What is a classloader and what is the role?

The class loader loads the bytecode file (. Class)

2. Types of Class Loaders

There are three types of classloader, unlike the same loader loading different

1) BootStrap: Boot class loader: Load is the most basic file

2) Extclassloader: extension ClassLoader: Loading files that are basic

3) Appclassloader: Application ClassLoader: Three-party jar package and write Java file yourself

How do I get the classloader? Focus

ClassLoader byte-code object. getClassLoader ();

 Public classDemo { Public Static voidMain (string[] args) {//class loader to get demo bytecode filesClass Clazz= Demo.class;//get the Bytecode object for demoClassLoader ClassLoader= Clazz.getclassloader ();//Get class loader//getresource parameter path relative to classes (SRC)//get any resources under classes (SRC)String Path= Classloader.getresource ("Com/itheima/classloader/jdbc.properties"). GetPath (); //Classloader.getresourceasstream ("");System.out.println (path); }}

Second, the annotated @xxx1. What are annotations, annotation functions

Annotations are syntax that conforms to a certain format @xxxx

Annotation effect:

Note: Read the program clearly----to the programmer to see

Note: For the JVM, see the machine.

The most mainstream application of annotations in the present case: instead of configuration files

About the advantages and disadvantages of configuration file and annotation development:

Advantages of annotations: high development efficiency and low cost

Note disadvantage: Large coupling and not conducive to post-maintenance

Enterprise trends: Mixed use, infrequently modified can be in the form of annotations.

2. Annotations provided by Jdk5

@Override: Tells the compiler that this method overrides the parent class's

@Deprecated: Label obsolete

@SuppressWarnings: Suppressing warnings

Deprecation, ignoring outdated

Unused, ignoring not using

Rawtypes, ignoring type safety

All, ignoring all

.....

Problems found:

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

3. Custom annotations (Learn)

1) How to write a custom annotation

2) How to use annotations

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

(1) Write an annotation

Keywords: @interface

Attributes of Annotations:

Syntax: return value name ();

Note: If the name of the property is value and the property value of the annotation has one then the value can be omitted when using annotations

The annotation attribute type can only be one of the following

1. Basic types

2.String

3. Enumeration type

4. Annotation type

5.Class type

6. One-dimensional array type of the above type

(2) using annotations

Above the class/method/field is @xxx

(3) Parsing classes that use annotations

To intervene in a concept: meta-annotations: annotations that represent modified annotations, effects: attributes of restricted annotations

@Retention

Source: Annotations are visible at the source level

Class: Annotations are visible at the byte-code file level

Runtime: Annotations are visible throughout the run phase

@Target

Represents the scope of a callout adornment: used on a class, used on a method, used on a field

Field: This annotation is available on fields

Method: This annotation can be used on methods

Type: This annotation can be used on classes/interfaces

Note: To parse a class that uses annotations, the annotation's retention must be set to runtime

On the essence of annotation parsing: Resolving attribute values from annotations

Bytecode objects exist in methods that are related to getting annotations

isannotationpresent ( Class <? extends Annotation> annotationClass) 判断该字节码对象身上是否使用该注解了

getannotation ( Class <A> annotationClass) : Gets the annotated object on the Bytecode object

4. Case-Custom Unit test @mytest
 Public classMytestparster { Public Static voidMain (string[] args)throwsillegalaccessexception, IllegalArgumentException, InvocationTargetException, instantiationexception {//Get TestdemoClass Clazz= Testdemo.class; //get all the methodsmethod[] Methods=Clazz.getmethods (); if(methods!=NULL){         //get annotations using the @mytest method          for(Method method:methods) {//determine if the method uses @mytest annotations            BooleanAnnotationpresent = Method.isannotationpresent (MyTest.class); if(annotationpresent) {//This method uses mytest annotations.Method.invoke (Clazz.newinstance (),NULL); }         }      }    }} 

Third, dynamic Agent 1. What is an agent (mediation)

Target object/proxied object------Homeowner: The real way to rent a house

Proxy object-------Black intermediary: A way to rent a house (call the landlord's rental method)

Object that executes the proxy object method----renting people

Process: We want to rent-----> Intermediary (Rental method)------> Homeowner (Rental method)

Abstraction: Calling Object-----> Proxy object------> Target Object

2. Dynamic Agent

Dynamic proxy: Instead of writing a proxy object manually, you do not need one by one to write the same method as the target object, which dynamically generates the proxy object in memory at run time. A proxy object at the------byte-code object level

API for Dynamic Agents:

There is a method in the JDK API that generates a dynamic proxy in a proxy newproxyinstance

static Object

newproxyinstance ( ClassLoader loader, Class <?>[] interfaces, invocationhandler h)

Return value: Object is the surrogate

Parameter: Loader: Represents the same class loader as the target object-------target pair

Like. GetClass (). getClassLoader ()

Interfaces: An array of all interface bytecode objects that represent the implementation of the target object

H: Operation of the specific agent, Invocationhandler interface

Note: The proxy mode of the JDK implements the dynamic proxy target object must have an interface no interface can not implement the JDK version of the dynamic agent

Example one:

 Public classproxytest {@Test Public voidtest1 () {//Get dynamic Proxy objects----Create a virtual proxy object for target dynamically in memory at run time//Objproxy is a proxy object that determines who the proxy object is based on the parameterstargetinterface Objproxy=(Targetinterface) proxy.newproxyinstance (Target.class. getClassLoader (),//the same class loader as the target object            NewClass[]{targetinterface.class},            NewInvocationhandler () {//invoke represents the method that executes the proxy object@Override//method: Methods Bytecode object representing the target object//args: Parameters for methods that represent the response of the target object                 PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Logic before the target method"); //methods for executing target objectsObject Invoke= Method.invoke (NewTarget (), args); System.out.println ("Logic after the target method"); returninvoke;           }            }         );      Objproxy.method1 (); String method2=objproxy.method2 ();   System.out.println (METHOD2); }  }

Example two:

 Public classProxyTest2 { Public Static voidMain (string[] args) {FinalTarget target =NewTarget (); //dynamically creating proxy objectsTargetinterface Proxy=(Targetinterface) proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass () . Getinterfaces (),NewInvocationhandler () {@Override//How many times have they been executed? -------See how many proxy objects are called//proxy Object invocation interface The appropriate method is to invoke the Invoke                /** Proxy: Is the Agent Object * Method: Represents the target method of the Bytecode object * args: Represents the call to the target method when the parameter */                 PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//Reflective Knowledge pointsObject Invoke= Method.invoke (target, args);//the corresponding method of the target object//Retrun Returns the value to the proxy object                   returninvoke;           }            }         ); Proxy.method1 ();//Call Invoke---Method: args:null return value for target object method1 nullString method2= Proxy.method2 ();//Call the Invoke---method: args:null return value for the target object method2 method2      intmethod3 = proxy.method3 (100);////Call Invoke-----method: args:object[]{100} return value of target object method3System.out.println (METHOD2);   System.out.println (METHOD3); }}

3. Case-resolution of the global encoding

 Public classEncodingfilterImplementsfilter{@Override Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {FinalHttpServletRequest req =(httpservletrequest) request; //using dynamic Agents to complete global encodingHttpServletRequest Enhancerequset=(HttpServletRequest) proxy.newproxyinstance (Req.getclass (). getClassLoader (), Req.getclass (). GE Tinterfaces (),NewInvocationhandler () {@Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//enhancements to the GetParameter methodString name= Method.getname ();//gets the method name of the target object                   if("GetParameter". Equals (name)) {String Invoke= (String) method.invoke (req, args);//garbled//transcodingInvoke=NewString (Invoke.getbytes ("iso8859-1"), "UTF-8"); returninvoke; }                   returnMethod.invoke (req, args);                }            }                        );                     Chain.dofilter (Enhancerequset, response); //request.setcharacterencoding ("UTF-8"); //enhance the GetParameter method of the request before passing the request      /** Decorator Mode (PACKAGING) * * 1, enhanced class and enhanced class to implement unified interface * 2, in the enhanced class to pass in the enhanced class * 3, need to enhance the method overrides do not need to enhance the method calls the enhanced object *       */           //objects that are enhanced//httpservletrequest req = (httpservletrequest) request; //Enhanced Objects//enhancerequest enhancerequest = new Enhancerequest (req); //Chain.dofilter (enhancerequest, response);} @Override Public voiddestroy () {} @Override Public voidInit (Filterconfig filterconfig)throwsservletexception {}}classEnhancerequestextendshttpservletrequestwrapper{PrivateHttpServletRequest request;  Publicenhancerequest (HttpServletRequest request) {Super(Request);  This. Request =request; }     //for getparaameter Enhancement@Override Publicstring GetParameter (string name) {string parameter= Request.getparameter (name);//garbled      Try{parameter=NewString (Parameter.getbytes ("iso8859-1"), "UTF-8"); } Catch(unsupportedencodingexception e) {e.printstacktrace (); }      returnparameter; }  }

"Javaweb Learning Notes" 25_ Foundation enhancement: classloader, annotations @xxx, and dynamic proxies

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.