Understanding of Java reflection and dynamic proxy

Source: Internet
Author: User
Tags stringbuffer idf

First, what is the reflection mechanism?

The official definition of reflection is this: in the running state, for any class, you can know all the properties and methods of this class, any object can be invoked through the reflection mechanism of a class of any method, the dynamic acquisition of class information and the function of dynamic call class object method is called Java reflection mechanism.

In layman's words, for the JVM,. java files must first be compiled into a. class file to be executed by the JVM, so the type of the object will be specified, such as user user, in the process of compiling to a. class file. So what if I want to get the type of the object in the process of running the code? Or how does the program load a particular class during the run? This involves the reflection mechanism of Java, which provides a way for us to get a type attribute when the code is running.

Second, the use of reflection

The JDK provides three ways to get the class of an object, in terms of the user user

1.user.getclass (), this is the method inside the object class

The 2.user.class property, any data type, base data type, or abstract data type, can be used in this way to get the class

3.class.forname (""), the class class provides a way for us to get to the object class through the class name

The three methods use the most of the third, then after getting to the class, the class provides a lot of access to the class properties, methods, constructs the method of the API.

1. Get all the properties

//get the entire classClass C = class.forname ("Java.lang.Integer"); //get all the properties? field[] fs =C.getdeclaredfields (); //defines a variable-length string used to store propertiesStringBuffer SB =NewStringBuffer (); //stitching each property into this string by appending the method//the outermost public definitionSb.append (Modifier.tostring (C.getmodifiers ()) + "class" + c.getsimplename () + "{\ n"); //each of the properties inside             for(Field field:fs) {sb.append ("\ t");//SpaceSb.append (Modifier.tostring (Field.getmodifiers ()) + "");//gets the modifier for the property, such as Public,static, and so onSb.append (Field.gettype (). Getsimplename () + "");//the name of the type of the propertySb.append (Field.getname () + "; \ n");//Name of property + carriage return} sb.append ("}");  System.out.println (SB); 

2. Get a specific property

 //Get classClass C = class.forname ("User"); //Get ID PropertyField IdF = C.getdeclaredfield ("id"); //instantiate this class to assign OObject o =c.newinstance (); //Break PackageIdf.setaccessible (true);//using the reflection mechanism can break the encapsulation and cause the properties of the Java object to be unsafe. //assigns the id attribute of the O object to "Max"Idf.set (O, "110");//Set//GetSystem.out.println (Idf.get (o));

3. Get the method

getdeclaredmethods ()    gets all the methods Getreturntype ()    get the return type of the method Getparametertypes ()    Gets the passed-in parameter type of the method Getdeclaredmethod ("method name", Parameter type.) class ,......)    Get the specific Method getdeclaredconstructors ()    gets all the constructor method getdeclaredconstructor (parameter type. class ,......)    Gets the specific constructor method Getsuperclass ()    Gets the parent class of a class Getinterfaces ()    gets the interface of a class implementation

Third, the role of reflection and dynamic agent

The Reflection summary is: 1. Dynamically create an instance of the class, bind the class to an existing object, or get the type from an existing object. 2. An application needs to load a specific class from a particular assembly at run time.

So what is a dynamic agent? First, the answer to Baidu: Dynamic proxy, is to invoke the proxy class method and properties by creating a runtime class object from the class class that the object loads in memory.

Proxy mode definition: Provides a proxy for other objects to control access to this object. In some cases, an object does not fit or cannot directly reference another object, and a proxy object can act as an intermediary between the client and the target object. And the proxy mode is divided into static agent and dynamic agent, first say static agent.

Static proxy The popular point is to hand-write a proxy class, and dynamic agents do not use our handwriting, but rely on the Java reflection mechanism, following a demo example.

Demo structure

  

Subject is a common interface with an abstract dosomething () method, and Subjectimpl.java is its common implementation class, as shown below.

    

  

And Handproxy.java is Subjectimpl static proxy class, instead of Subjectimpl to complete the work of dosomething, as shown below

  

The advantage of this is that for the DoSomething method, I use the static proxy class to do it, and I can arbitrarily insert something I need to do, such as logging.

Then Autoproxy.java is the dynamic proxy class, as shown below.

  

In this first want to do dynamic proxy, we must first implement this Invocationhandler interface, and then we mainly look at the bind method, the parameter tar is an object type, that is, the object needs to be proxied Subjectimpl,

There is a proxy class in the method, this proxy class provides a lot of methods, here we use the Newproxyinstance method, it has three parameters, the first is the class constructor of the proxy class, the second refers to the interface of the proxy class, that is, the subject interface, The third is the class that implements this proxy, and here is the class. Specifically, this approach performs the following three steps:

1. Generate a byte code that implements all the interfaces in the parameter interfaces and inherits the proxy class, and then loads the proxy class with the ClassLoader in the parameter.

2. Use the constructor of the proxy class parent class proxy (Invocationhandler h) to create an instance of the proxy class, passing in the subclass of our custom Invocationhandler.

3. Return this proxy class instance, because the proxy class we constructed implements all the interfaces in interfaces (that is, the Subject.getclass (). Getinterfaces ()) in our program. The returned proxy class can therefore be strongly turned into a subject type to invoke the method defined in the interface.

When invoking each method of each proxy class, we use the Invoke method of the reflection to tune H (that is, the Invoke method overridden in our custom Invocationhandler subclass), passing the proxy class instance, the interface method, the invocation parameter list with the parameter, This allows us to implement a uniform wrapper for all methods in the overridden Invoke method.

To summarize, the advantages of static proxies are clear and understandable, but if the business code is many, then in the proxy class must be called all over again, very troublesome. and dynamic agent, using the Java reflection mechanism, dynamically generated a proxy class, directly invoke the proxy method can be.

Iv. Summary

The reflection of this piece is the blogger recently in the framework of the source code is always encountered this kind of problem so deliberately to tidy up a bit, there are some things in fact I also study is not very deep, dynamic agent side of the source still need to dig deep, if there is great God found the wrong place, also please advise, thank you.

Understanding of Java reflection and dynamic proxy

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.