1. Reflection in java
1. Load the class's attributes and method instance code through reflection:
/** * java.lang.Class is the source of reflection* We created a class and generated the corresponding class file by compiling (javac.exe). After we load (jvm's class loader) this class file* After this class file is loaded into memory, it is a runtime class with a cache area. This runtime class is an instance of Class* Each runtime class is only loaded 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 type Field field = clazz.getDeclaredField("id"); // The attribute is non-public type Field[] fields = clazz.getDeclaredFields(); // Get all declared properties of the runtime class itself (the parent class cannot do). The parent class uses clazz.getFields(); for (Field field2 : fields) { int i = field2.getModifiers(); String type = Modifier.toString(i);// Get the data type of 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 method = clazz.getMethod("setId", Integer.class); method.invoke(studentExam, 123); // Call the specified method of the runtime class Method[] methods = clazz.getMethods(); // Get all methods declared as public in all runtime classes and their parent classes Method[] methods2 = clazz.getDeclaredMethods();// Get the method declared in the runtime class itself for (Method method2 : methods) { System.out.println(method2.getName()); } // * Get the object's runtime class through the getClass() method of the object, Exam exam = new Exam(); Class clazzExam = exam.getClass();2. ClassLoader
/** * Description: Class loader, load the xx.properties file, and read the data * @param * @author xiazhongwei * @data September 29, 2016: 5:32:56 pm * @return */ public void classLoader() throws IOException { //Method 1. Load ClassLoader from the current project loader = this.getClass().getClassLoader(); // The path is written under the package: com//able//onlineExam//resources//config.properties InputStream 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 the proxy class and the target object are determined during compilation, which is not conducive to the expansion of the program. At the same time, each proxy class can only serve one interface, so too many proxy will inevitably occur in program development.
Dynamic proxy: The client 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.
Principles of agent design pattern:
Use a proxy to wrap the object, and then replace the original object with that proxy object. Any call to the original object must be through the proxy, whether and when the proxy object determines whether and when the method is called
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 of dynamic proxy interface Subject{ void action();}// Class RealSubject implements Subject{ @Override public void action() { System.out.println("I am the proxy class, remember to execute me..."); } } class MyInvocationHandler implements InvocationHandler{ Object object;// Declaration of the object of the proxy class of the interface/** * Description: ① Instantiate the proxy object ② Return a proxy class object* @param * @author xiazhongwei * @data September 29, 2016: 4:13:43 pm * @return */ public Object bind(Object object){ this.object = object; return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), this); } /** * When a call to the rewritten method is initiated through an object of the proxy class, it will be converted into a call to the following invok method */ @Override public Object invoke(Object proxy, Method 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 { @Override public int add(int i, int j) { int result = i + j; return result; } @Override public int sub(int i, int j) { int result = i - j; return result; } @Override public int mul(int i, int j) { int result = i * j; return result; } @Override public int div(int i, int j) { int result = i / j; return result; } } package com.atguigu.spring.aop; public class ArithmeticCalculatorLoggingImpl implements ArithmeticCalculator { @Override public 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; } @Override public 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; } @Override public 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 begins with [" + i + "," + j + "]"); int result = i * j; System.out.println("The method mul ends with " + result); return result; } @Override public 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 ArithmeticCalculatorLoggingProxy { //Object to be proxy private ArithmeticCalculator target; public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator target) { super(); this.target = target; } //Return the proxy object public ArithmeticCalculator getLoggingProxy(){ 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, what methods are there in it. Class [] interfaces = new Class[]{ArithmeticCalculator.class}; // When calling the methods of the proxy object, execute the following code InvocationHandler h = new InvocationHandler() { /** * proxy: proxy object. This object is generally not used * method: The method being called* args: The parameters passed in the call method*/ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // A method of the proxy object will not be called directly inside the method. proxy.toString() will cause a dead 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)); //Calling the target method Object result = null; try { //Pre-notification result = method.invoke(target, args); //Return notification, you can access the return value of the method} catch (NullPointerException e) { e.printStackTrace(); //Exception notification, you can access the exception of the method} //Post-notification. Because the method may have an exception, the return value of the method cannot be accessed //Print log System.out.println("[after] The method ends with " + result); return result; } }; /** * loader: The class loader used by the proxy object. * interfaces: Specify the type of the proxy object. That is, what methods can be found in the proxy proxy object. * h: When calling the method of the proxy object, how should it respond? In fact, it is to call the invoke method of InvocationHandler*/ 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 of dynamic proxy interface Subject{ void action();}// Class RealSubject implements Subject{ @Override public void action() { System.out.println("I am the proxy class, remember to execute me..."); } } class MyInvocationHandler implements InvocationHandler{ Object object;// Declaration of the object of the proxy class of the interface/** * Description: ① Instantiate the proxy object ② Return a proxy class object* @param * @author xiazhongwei * @data September 29, 2016: 4:13:43 pm * @return */ public Object bind(Object object){ this.object = object; return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), this); } /** * When a call to the rewritten method is initiated through an object of the proxy class, it will be converted into a call to the following invok method */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object returnObject = method.invoke(object, args); return returnObject; }}Thank you for reading this article, I hope it can help you. Thank you for your support for this site!