Java Reflection and Proxy

Source: Internet
Author: User
Tags throwable

The Java Reflection mechanism and dynamic proxy make java more powerful, andSpring core concept IoCandAOP are implemented by reflection mechanism and dynamic proxy.

1 Java Reflection

Example:

User User =NewUser (); User.settime5flag ("Test"); Class<?> cls = Class.forName ("Com.test.User");//The interface must be public, whether or not it is used inside this class! or use Cls.getdeclaredmethod (), or iterate through the modification of accessibilitymethod = Cls.getmethod ("Gettime5flag"); String res1=(String) method.invoke (user); System.out.println (res1);//When it comes to basic types such as int, use int.class! integer.class!=int.class! method = Cls.getmethod ("Settime5flag", String.class); Method.invoke (User,"Rollen"); method= Cls.getmethod ("Gettime5flag"); String Res2=(String) method.invoke (user); System.out.println (res2);

Get the full package name and class name from an object:

User.getclass (). GetName (); // full path class name User.getclass (). Getsimplename (); // class name without a package name

Get class:
Class.forName ("Com.test.User"); Com.test.User. class ; User.getclass ();

Instantiating an object from class
User user = (user) cls.newinstance (); // must have no parameter constructor

Get all constructors
// Return Cons[0].newinstance () in declared order ; // no display declaration, there is a default constructor

Get all the interface that a class implements
class<?> intes[] = cls.getinterfaces ();

Get parent class
Cls.getsuperclass ();

Get modifier
int mo = cls.getmodifiers (); int mo = cons[0].getmodifiers (); int mo = method.getmodifiers (); Modifier.tostring (MO);

Get method parameters
method.getparametors (); cons[0].getparametors ();

Get method Parameter type
method.getparametortypes (); cons[0].getparametortypes ();

Get all exception types thrown by a method declaration
Method.getexceptiontypes ();

Get all the properties of this type of declaration
// including privatefield[0].getmodifiers (); field[0].gettype ();

Gets all the exposed properties of this class, including the parent class declaration, the interface Declaration, all the public properties of this class declaration

Cls.getfields ();

Sets the specified properties to access

Field.setaccessible (true); Field.set (obj, ' ces '); Field.get (obj) ;

* GetFields () differs from Getdeclaredfields (): GetFields () can only access fields declared as public in the class, private fields that cannot be accessed, and access to public fields inherited from other classes; Getdeclaredfields () can access all fields in a class, regardless of public,private,protect, but cannot access fields inherited from other classes

* GetMethods () differs from Getdeclaredmethods (): GetMethods () can only access methods declared as public in a class, private methods that it cannot access, and access to public methods inherited from other classes; Getdeclaredmethods ( ) can access all the fields in the class, regardless of public,private,protect, and cannot access methods inherited from other classes

* GetConstructors () differs from getdeclaredconstructors (): GetConstructors () can only access constructors declared as public in a class; Getdeclaredconstructors () Access to all constructors in the class, regardless of Public,private,protect

Getting and modifying the information of an array by reflection
int [] temp={1,2,3,4,5}; Class<?> demo = temp.getclass (). Getcomponenttype (); System.out.println ("array type:" +demo.getname ()); // int SYSTEM.OUT.PRINTLN ("Array Length:" +array.getlength (temp)); // 5 System.out.println ("The first element of the array:" +array.get (temp, 0)); // 1 Array.set (temp, 0, +); System.out.println ("The first element of a modified array is:" +array.get (temp, 0)); //  -

Get array type
Cls.getcomponenttype ();

Determine if the array type
Cls.isarray ();

2 Java Proxy

Proxy mode is a common Java design pattern, its characteristic is that the proxy class and the delegate class have the same interface, the proxy class is mainly responsible for the delegate class preprocessing messages, filtering messages, forwarding messages to the delegate class, and post-processing messages. There is usually an association between the proxy class and the delegate class, and the object of a proxy class is associated with an object of a delegate class, and the object of the proxy class does not actually implement the service, but instead provides a specific service by invoking the related method of the object of the delegate class.

The proxy class can be divided into 2 types according to the agent's creation period.

    • Static proxy: The source code is generated automatically by the programmer or a specific tool, and then compiled. Before the program runs, the. class file for the proxy classes already exists.
    • Dynamic Proxy: The bytecode is dynamically generated by the Java reflection mechanism while the program is running.
2.1 Static Proxies
 Public InterfaceCount { Public voidquerycount ();} Public classCountimplImplementsCount { Public voidQuerycount () {System.out.println ("View Account Method ..."); }}//proxy class Public classCountproxyImplementsCount {PrivateCountimpl Countimpl;  Publiccountproxy (Countimpl countimpl) { This. Countimpl =Countimpl; } @Override Public voidQuerycount () {System.out.println ("Before transaction processing"); Countimpl.querycount (); //the method of invoking the delegate class;System.out.println ("After Transaction"); }}//Test Class Public classTestcount { Public Static voidMain (string[] args) {Countimpl Countimpl=NewCountimpl (); Countproxy Countproxy=NewCountproxy (Countimpl);       Countproxy.querycount (); }}

Observation code can find that each proxy class can only serve one interface, so that the development of the program will inevitably generate too many agents, and all the agent operation in addition to the method called, the other operations are the same, then it must be duplicated code. The best way to solve this problem is to complete the proxy function through a proxy class, which must be done using dynamic proxy.

2.2 Dynamic Agents

The bytecode of the dynamic proxy class is dynamically generated by the Java reflection mechanism when the program is run, without the programmer writing its source code manually. The dynamic proxy class not only simplifies programming, but also improves the scalability of the software system, because the Java reflection mechanism can generate any type of dynamic proxy class.

2.2.1 JDK Dynamic Agent

The proxy class and the Invocationhandler interface in the Java.lang.reflect package provide the ability to generate dynamic proxy classes.

Invocationhandler Interface:

Public interface Invocationhandler {
public object Invoke (Object Proxy,method method,object[] args) throws Throwable;
}

Parameter description:

Object proxy: Refers to the objects being proxied.
Method: Methods to invoke
object[] args: Parameters required for method invocation

The subclass of the Invocationhandler interface can be imagined as a proxy's final operation class, replacing the Proxysubject.

Proxy class:

The proxy class is an action class that specifically completes the proxy, which can be used to dynamically generate an implementation class for one or more interfaces, which provides the following operations:

public static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h) throws IllegalArgumentException

Parameter description:

ClassLoader Loader: Class loader
Class<?>[] Interfaces: Get all the interfaces
Invocationhandler h: Get subclass instance of Invocationhandler interface

If you want to complete a dynamic proxy, you first need to define a subclass of the Invocationhandler interface to accomplish the agent's specific operation.

InterfaceSubject { PublicString say (string name,intAge );}classRealsubjectImplementsSubject {@Override PublicString say (string name,intAge ) {        returnName + "" +Age ; }}//JDK Dynamic proxy classclassMyinvocationhandlerImplementsInvocationhandler {PrivateObject target =NULL; //binds a delegate object and returns a proxy class     Publicobject bind (object target) { This. target =Target; returnproxy.newproxyinstance (Target.getclass (). getClassLoader (),
Target.getclass (). Getinterfaces (), This);//to bind the interface (Cglib compensate for this)} @Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("before Method!"); Object Temp=Method.invoke (target, args); System.out.println ("After method!"); returntemp; }}classHello { Public Static voidMain (string[] args) {Myinvocationhandler demo=NewMyinvocationhandler (); Subject Sub= (Subject) demo.bind (Newrealsubject ()); String Info= Sub.say ("Rollen", 20); SYSTEM.OUT.PRINTLN (info); }}

However, the dynamic proxy of the JDK relies on the interface, and if some classes do not implement the interface, then the JDK proxy cannot be used, which will use the Cglib dynamic proxy. 2.2.2 Cglib Dynamic Agent

The dynamic agent mechanism of the JDK can only broker the class that implements the interface, and the class without implementing the interface cannot implement the dynamic proxy of the JDK.

Cglib is implemented for a class to implement the proxy, which is the principle of generating a subclass for the specified target class and overriding the method implementation enhancements , but because inheritance is used, the final decorated class cannot be proxied.

 Public InterfaceBookfacade { Public voidAddbook ();}  Public classBOOKFACADEIMPL1 { Public voidAddbook () {System.out.println ("An ordinary way to add books ..."); } }  ImportJava.lang.reflect.Method; ImportNet.sf.cglib.proxy.Enhancer;ImportNet.sf.cglib.proxy.MethodInterceptor;ImportNet.sf.cglib.proxy.MethodProxy;//cglib Dynamic proxy class Public classBookfacadecglibImplementsMethodinterceptor {PrivateObject Target; //binds a delegate object and returns a proxy class     Publicobject GetInstance (object target) { This. target =Target; Enhancer Enhancer=Newenhancer (); Enhancer.setsuperclass ( This. Target.getclass ()); //callback MethodEnhancer.setcallback ( This); //Create a proxy object        returnenhancer.create (); } @Override//callback Method     PublicObject Intercept (Object obj, Method method, object[] args, methodproxy proxy)throwsthrowable {System.out.println ("Things start."); Object Temp=proxy.invokesuper (obj, args); System.out.println ("The end of things."); returntemp; } }  Public classTestcglib { Public Static voidMain (string[] args) {bookfacadecglib cglib=NewBookfacadecglib (); BOOKFACADEIMPL1 Bookcglib= (BOOKFACADEIMPL1) cglib.getinstance (NewBookFacadeImpl1 ());     Bookcglib.addbook (); } }

Reference: 1.11900000043260402.http://blog.csdn.net/hintcnuie/article/details/10954631

Java Reflection and Proxy

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.