Learn Java reflection with me--Four steps

Source: Internet
Author: User


in the previous three articles we will reflect the basic knowledge and through reflection to get the structure of the running class, such as, properties, methods, parent class, interface, annotations and other content, and how to invoke the Run class by reflection of the specified properties and methods, this article we learn a typical running reflection, dynamic agent and AOP the combination.  

AOP dynamic Agent

let's start with a case where the code snippet 1 , 2 , 3 all contain the same code snippet, and the previous method is done with a complex paste of repeated code snippets,


The situation described above is bound to be improved, and we pull out the duplicated code so that the code snippet 1 , 2 , 3 by invoking a method call, you invoke the duplicated snippet of code that is drawn out, so that the code snippet is compared to the diagram above 1 , 2 , 3 and duplicated code snippets, but the code snippet 1 , 2 , 3 Coupled with the code that was drawn out, such as:


the ideal effect is: Code Snippets 1 , 2 , 3 that is, the available execution methods A , and it doesn't have to be called in a method call or hard-coded way in the program, and AOP dynamic agents can be a good solution to this problem.

about the AOP The implementation of dynamic agent is commonly used JDK The reflection also has CGLib , the difference is that the former cannot be a class without an interface and CGlib Yes, we will not say more, because this article is mainly to apply the reflection in the previous three articles, all of our dynamic agents with JDK self-brought reflection to achieve. All next we will use the JDK dynamic agent to solve this problem.

Specific Implementation


First is the agent interface Hello:

<span style= "font-family:kaiti_gb2312;" >package com.tgb.state;/** *  * @author kang * */public interface Hello {public void Say (String name); </span>


Agent Interface Hello the implementation class Helloimpl :

<span style= "font-family:kaiti_gb2312;" >package Com.tgb.state;public class Helloimpl implements Hello {@Overridepublic void Say (String name) { System.out.println (This.getclass () + "  hello!" +name);}} </span>



Pull out of the generic code class Servicebean:

<span style= "font-family:kaiti_gb2312;" >package com.tgb.dynamic.jdk;import java.lang.reflect.method;import java.util.hashmap;/** * Service Bean, is a function that needs to be reused in AOP * @author Kang * */public class Servicebean {//The object hashmap<string before the proxy object method, object> Beforebeans = NE W hashmap<string, object> ();//The Object hashmap<string after the proxy object method is set, object> Afterbeans = new hashmap<string, Object> ();//Method Hashmap<string the object before the proxy object method, string> beforemethods = new hashmap<string, string> ();// Methods for objects after the proxy object method hashmap<string, string> aftermethods = new hashmap<string, string> ();p ublic Void before () Throws Exception{for (hashmap.entry<string, object> entry:beforeBeans.entrySet ()) {String Beankey = Entry.getkey (); Object Beforebean = Entry.getvalue (); String Beforemethodvalue = Beforemethods.get (Beankey);//system.out.println ("Beforemethodvalue:" +beforeMethodValue );//Use reflection to get the class to execute method Beforemethod = Beforebean.getclass (). GetMethod (Beforemethodvalue);//system.out.println ("Beforemethod:" +beforemethod);//Use reflection to execute the method Beforemethod.invoke (Beforebean) that the running class needs to execute;} System.out.println (This.getclass () + "before");} public void After () throws Exception {for (hashmap.entry<string, object> entry:afterBeans.entrySet ()) {String bean Key=entry.getkey (); Object afterbean=entry.getvalue (); String Aftermethodvalue=aftermethods.get (Beankey);//system.out.println ("Aftermethodvalue:" +afterMethodValue);// Use reflection to get the class to execute method Aftermethod = Afterbean.getclass (). GetMethod (Aftermethodvalue);//system.out.println (" Aftermethod: "+aftermethod");//Use reflection to execute the method Aftermethod.invoke (Afterbean) that the running class needs to execute;} System.out.println (This.getclass () + "after");} Public hashmap<string, Object> Getbeforebeans () {return beforebeans;} public void Setbeforebeans (hashmap<string, object> beforebeans) {This.beforebeans = Beforebeans;} Public hashmap<string, Object> Getafterbeans () {return afterbeans;} public void Setafterbeans (hashmap<string, object> afterbeans) {This.afterbeans = Afterbeans;} PubLic hashmap<string, string> getbeforemethods () {return beforemethods;} public void Setbeforemethods (hashmap<string, string> beforemethods) {this.beforemethods = Beforemethods;} Public hashmap<string, String> Getaftermethods () {return aftermethods;} public void Setaftermethods (hashmap<string, string> aftermethods) {this.aftermethods = Aftermethods;}} </span>


Processing class myinvokationhandler:


<span Style= "font-family:kaiti_gb2312;" >package Com.tgb.dynamic.jdk;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.Method;import java.lang.reflect.proxy;/** * Processing class, used to load multiplexed code classes * @author Kang * */public class Myinvokationhandler implements Invocationhan Dler{private Servicebean Servicebean;private Object Target;public Object Gettarget () {return target;} public void Settarget (Object target) {this.target = target;} @Overridepublic object Invoke (Object proxy, Method method, object[] args) throws Throwable {Servicebean.before (); Result =method.invoke (target, args); Servicebean.after (); return result;} Public Servicebean Getservicebean () {return servicebean;} public void Setservicebean (Servicebean servicebean) {This.servicebean = Servicebean;}} </span> 

proxy classes for dynamically generated proxy objects myproxyfactory :


<span style= "font-family:kaiti_gb2312;" >package Com.tgb.dynamic.jdk;import Java.lang.reflect.proxy;public class Myproxyfactory {/** * Generate proxy Object * @return */@ Suppresswarnings ("unchecked") public static <T> T getproxy (Object Target,myinvokationhandler handler) {// Set the target object Handler.settarget (target) for myinvokationhandler;//Create and return a dynamic proxy object return (T) proxy.newproxyinstance ( Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), handler);}} </span>

 

Get here AOP Dynamic agent of the whole class is already there, the careful classmate will find that Servicebean service class is a bit complicated, because we are here to do the service class abstraction, so that the service class can be used in the use of reflection to dynamically load the need to reuse the function class, the reflection code is we in the first three articles learned.

Let's take a look at the reusable functional classes that require dynamic loading Hi Impl :


<span style= "font-family:kaiti_gb2312;" >package com.tgb.state;public class himanage{public void Hi () {System.out.println (This.getclass () + "before method" + " Hi method ");} public void Bye () {System.out.println (This.getclass () + ' after method ' + ' Bye Method ');}} </span>

Next, look at our client code:


<span style= "font-family:kaiti_gb2312;" >package Com.tgb.dynamic.jdk;import Java.util.hashmap;import Com.sun.org.apache.bcel.internal.generic.NEW; Import Com.tgb.state.himanage;public class Client4 {public static void main (string[] args) {//---------------load Reusable function class- -------------------------hashmap<string, object> Beforebeans = new hashmap<string, object> (); hashmap<string, object> Afterbeans = new hashmap<string, object> (); hashmap<string, string> beforemethods = new hashmap<string, string> (); hashmap<string, string> aftermethods = new hashmap<string, string> (); Beforebeans.put ("HiManage", new HIIMPL1 ()); Afterbeans.put ("Himanage", New HiImpl1 ()), Beforemethods.put ("Himanage", "HI"); Aftermethods.put (" Himanage "," Bye "); Servicebean Servicebean = new Servicebean (); Servicebean.setbeforebeans (Beforebeans); Servicebean.setafterbeans ( Afterbeans); Servicebean.setbeforemethods (beforemethods); Servicebean.setaftermethods (afterMethods);//---------- --------LOAD REUSABLE Function Class-----------------------//will be loaded after the completion of the reusable function class, set to the processing class Myinvokationhandler handler = new Myinvokationhandler (); Handler.setservicebean (Servicebean);//Generate proxy object Hello Helloproxy=myproxyfactory.getproxy (new Helloimpl (), handler) ; Helloproxy.say ("Zhangsan");}} </span>

operation Result:


The Before method of class Com.tgb.state.HiManage Hi method

Class Com.tgb.state.HelloImpl Hello!zhangsan

The After method bye method for class Com.tgb.state.HiManage

    To here a lang= zh-cn "en-US" lang= with jdk aop " reflection Lang= "ZH-CN" > dynamic agent completed, 3 in the left of the hello helloimpl is the proxy class, the rightmost servicebean servicebean himanage 1 , and line 2 hello himanage dynamic loading, which together implements our aop dynamic agent.


PostScript

through this altogether four articles, we have the knowledge of reflection through concrete Demo The code is learned, including class object creation, class object instance generation, and class The concrete structure of the class such as constructor, property, method, annotation, parent class, implement interface and so on, and finally introduces a typical application of reflection . AOP dynamic agents, about reflection first introduced to this.


Learn Java reflection with me--Four steps

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.