Reflection and dynamic proxy, reflection dynamic proxy

Source: Internet
Author: User

Reflection and dynamic proxy, reflection dynamic proxy
I. Reflection in java 1. Loading class attributes and methods through reflection example code:

/*** Java. lang. class is the source of reflection * we have created a class, compiled (javac.exe to generate the corresponding classfile, and then loaded through java.exe (jvm class Loader) This Class file * after this class file is loaded to the memory, it is a runtime class, there is a cache zone, this Class skill is a Class instance * Each runtime Class is loaded only once, */Class <StudentExam> clazz = StudentExam. class; StudentExam studentExam = clazz. newInstance (); System. err. println (studentExam); System. out. println (clazz); // Field field = clazz. getField ("id"); // call the specified attribute of the runtime class through the attribute: the attribute is public Field field = clazz. getDeclaredField ("id"); // The attribute is non-public Field [] fields = clazz. getDeclaredFields (); // get all declared attributes of the runtime class itself (the parent class does not work). The parent class uses clazz. getFields (); for (Field field2: fields) {int I = field2.getModifiers (); String type = Modifier. toString (I); // obtain the data type of the field attribute System. out. println (type);} field. setAccessible (true); field. set (studentExam, 11); System. err. println (studentExam. getId (); // call the specified Method of the runtime class through reflection method = clazz. getMethod ("setId", Integer. class); method. invoke (studentExam, 123); // call the specified Method of the runtime class [] methods = clazz. getMethods (); // obtain the Method [] methods2 = clazz. getDeclaredMethods (); // obtain the Method declared in the class of the runtime class for (Method method2: methods) {System. out. println (method2.getName ();} // * Get the runtime Class of the object through the getClass () method of the object, Exam exam = new Exam (); Class clazzExam = exam. getClass ();
2. ClassLoader
/*** Description: Class Loader, which loads xx. properties file, and read data * @ param * @ author xiazhongwei * @ data September 29, 2016: 5:32:56 * @ return */public void classLoader () throws IOException {// method 1. Load ClassLoader loader = this from the current project. getClass (). getClassLoader (); // The path is package write: com \ able \ onlineExam \ resources \ config. propertiesInputStream inStream = loader. getResourceAsStream ("config. properties "); // method 2. Load the File from the specified path // FileInputStream fileInputStream = new FileInputStream (new File (" config. properties "); Properties properties = new Properties (); properties. load (inStream); // properties. load (fileInputStream); String prop = properties. getProperty ("domain"); System. out. println (prop );}
3. Dynamic proxy

Static Proxy: the types of proxy classes and target objects are determined during compilation, which is not conducive to program expansion. At the same time, each proxy class can only serve one interface, so that too many Proxies are generated during program development.

Dynamic Proxy: the customer calls methods of other objects through the proxy class, and dynamically creates the proxy object of the target class as needed when the program is running.

Principle of proxy design mode:

Use a proxy to wrap the object, and then replace the original object with the proxy object. Any call to the original object will go through the proxy. The proxy object determines whether or not to call the method.

Package com. test. junit; import java. lang. reflect. invocationHandler; import java. lang. reflect. method; import java. lang. reflect. proxy; public class ProxyTest {public static void main (String [] args) {RealSubject realSubject = new RealSubject (); MyInvocationHandler myInvocationHandler = new MyInvocationHandler (); Object object = myInvocationHandler. bind (realSubject); Subject subject = (Subject) object; subject. Action () ;}/// use interface Subject {void action () ;}// the class RealSubject implements Subject {@ Overridepublic void action () {System. out. println ("I Am a proxy class, remember to execute me .... ") ;}} Class MyInvocationHandler implements InvocationHandler {Object object; // declares the Object of the proxy class that implements the interface/*** Description: ① instantiate the Object to be proxy ② return a proxy class Object * @ param * @ author xiazhongwei * @ data September 29, 2016: 4:13:43 * @ return */public object bind (Object object) {this. object = object; return Proxy. newProxyInstance (object. getClass (). getClassLoader (), object. getClass (). getInterfaces (), this);}/*** when calling a method to be overwritten through an object of the proxy class, will be converted to calling the following invok Method */@ Overridepublic Object invoke (Object proxy, method, Object [] args) throws Throwable {Object returnObject = Method. invoke (object, args); return returnObject ;}}
4. Dynamic proxy and AOP

Example 1,

package com.atguigu.spring.aop;public interface ArithmeticCalculator {int add(int i, int j);int sub(int i, int j);int mul(int i, int j);int div(int i, int j);}

  

package com.atguigu.spring.aop;import org.springframework.stereotype.Component;@Component("arithmeticCalculator")public class ArithmeticCalculatorImpl implements ArithmeticCalculator {@Overridepublic int add(int i, int j) {int result = i + j;return result;}@Overridepublic int sub(int i, int j) {int result = i - j;return result;}@Overridepublic int mul(int i, int j) {int result = i * j;return result;}@Overridepublic int div(int i, int j) {int result = i / j;return result;}}

  

package com.atguigu.spring.aop;public class ArithmeticCalculatorLoggingImpl implements ArithmeticCalculator {@Overridepublic int add(int i, int j) {System.out.println("The method add begins with [" + i + "," + j + "]");int result = i + j;System.out.println("The method add ends with " + result);return result;}@Overridepublic int sub(int i, int j) {System.out.println("The method sub begins with [" + i + "," + j + "]");int result = i - j;System.out.println("The method sub ends with " + result);return result;}@Overridepublic int mul(int i, int j) {System.out.println("The method mul begins with [" + i + "," + j + "]");int result = i * j;System.out.println("The method mul ends with " + result);return result;}@Overridepublic int div(int i, int j) {System.out.println("The method div begins with [" + i + "," + j + "]");int result = i / j;System.out.println("The method div ends with " + result);return result;}}

  

Package com. atguigu. spring. aop; import java. lang. reflect. invocationHandler; import java. lang. reflect. method; import java. lang. reflect. proxy; import java. util. arrays; public class extends {// target of the object to be proxy private ArithmeticCalculator; public extends (ArithmeticCalculator target) extends super(%%%this.tar get = target;} // return the proxy object public ArithmeticCalculator getLoggingPro Xy () {ArithmeticCalculator proxy = null; // which class loader of the proxy object is responsible for loading ClassLoader loader = target. getClass (). getClassLoader (); // The type of the proxy object, that is, the method Class [] interfaces = new Class [] {ArithmeticCalculator. class}; // when calling the method in the proxy object, execute the following code InvocationHandler h = new InvocationHandler () {/*** proxy: proxy object. Generally, this Object * method: the Method being called * args: The parameter passed in to the call method */@ Overridepublic Object invoke (Object proxy, method Method, Object [] args) throws Throwable {// a method of the proxy object is not directly called within the method, proxy. toString () will cause an infinite loop to call the invoke method String methodName = method. getName (); // print the log System. out. println ("[before] The method" + methodName + "begins with" + Arrays. asList (args); // call the target method Object result = null; try {// pre-notification result = method. invoke (Target, args); // return notification, and the return value of the method can be accessed} catch (NullPointerException e) {e. printStackTrace (); // exception notification, which can be used to access method exceptions} // post notification. because the method can cause exceptions, the return value of the method cannot be accessed. // print the log System. out. println ("[after] The method ends with" + result); return result ;}};/*** loader: Class loader used by The proxy object. * Interfaces: Specifies the proxy object type. which methods can be used in proxy objects. * h: how to respond when calling the proxy object method is actually calling the InvocationHandler's invoke Method */Proxy = (ArithmeticCalculator) proxy. newProxyInstance (loader, interfaces, h); return proxy ;}}

  

package com.atguigu.spring.aop;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {// ArithmeticCalculator arithmeticCalculator = new ArithmeticCalculatorImpl();ArithmeticCalculator arithmeticCalculator = new ArithmeticCalculatorLoggingImpl();arithmeticCalculator = new ArithmeticCalculatorLoggingProxy(arithmeticCalculator).getLoggingProxy();int result = arithmeticCalculator.add(11, 12);System.out.println("result:" + result);result = arithmeticCalculator.div(21, 3);System.out.println("result:" + result);}}

Example 2,

Package com. test. junit; import java. lang. reflect. invocationHandler; import java. lang. reflect. method; import java. lang. reflect. proxy; public class ProxyTest {public static void main (String [] args) {RealSubject realSubject = new RealSubject (); MyInvocationHandler myInvocationHandler = new MyInvocationHandler (); Object object = myInvocationHandler. bind (realSubject); Subject subject = (Subject) object; subject. Action () ;}/// use interface Subject {void action () ;}// the class RealSubject implements Subject {@ Overridepublic void action () {System. out. println ("I Am a proxy class, remember to execute me .... ") ;}} Class MyInvocationHandler implements InvocationHandler {Object object; // declares the Object of the proxy class that implements the interface/*** Description: ① instantiate the Object to be proxy ② return a proxy class Object * @ param * @ author xiazhongwei * @ data September 29, 2016: 4:13:43 * @ return */public object bind (Object object) {this. object = object; return Proxy. newProxyInstance (object. getClass (). getClassLoader (), object. getClass (). getInterfaces (), this);}/*** when calling a method to be overwritten through an object of the proxy class, will be converted to calling the following invok Method */@ Overridepublic Object invoke (Object proxy, method, Object [] args) throws Throwable {Object returnObject = Method. invoke (object, args); return returnObject ;}}

  

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.