Java reflection mechanism and dynamic proxy make Java more powerful. Spring's core concepts IoC and AOP are implemented through reflection mechanism and dynamic proxy.
1 Java Reflection
Example:
User user = new User();user.setTime5Flag("test"); Class<?> cls = Class.forName("com.test.User");//The interface must be public, regardless of whether it is used internally in this class! Either use cls.getDeclaredMethod(), or traverse to modify accessibility Method method = cls.getMethod("getTime5Flag"); String res1 = (String) method.invoke(user); System.out.println(res1);//If you involve 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);Obtain the complete package and class name through an object:
user.getClass().getName();//Full path class name user.getClass().getSimpleName();//Class name without package name
Get class:
Class.forName("com.test.User");com.test.User.class;user.getClass(); Instantiate an object through classUser user = (User) cls.newInstance();//There must be a parameter constructorGet all constructors
Constructor<?> cons[]=cls.getConstructors(); //Return cons[0].newInstance() in declaration order; //No display declaration, then there is a default constructorGet all interfaces implemented by a class
Class<?> intes[] = cls.getInterfaces();Get the parent class
cls.getSuperClass();Get the modifier
int mo = cls.getModifiers();int mo = cons[0].getModifiers();int mo = method.getModifiers();Modifier.toString(mo);Get method parameters
method.getParameters();cons[0].getParameters();Get method parameter type
method.getParametorTypes();cons[0].getParametorTypes();Get all exception types thrown by the method declaration
method.getExceptionTypes();Get all properties declared in this class
Field[] field = cls.getDeclaredFields(); //Include privatefield[0].getModifiers(); field[0].getType();
Get all public attributes of this class, including parent class declaration, interface declaration, and all public attributes of this class declaration
cls.getFields();
Set the specified attribute to access
field.setAccessible(true);field.set(obj,'ces');field.get(obj);
* The difference between getFields() and getDeclaredFields(): getFields() can only access fields declared as public in the class. It cannot access private fields and can access public fields inherited from other classes. getDeclaredFields() can access all fields in the class, which has nothing to do with public, private, and protect, but cannot access fields inherited from other classes.
* The difference between getMethods() and getDeclaredMethods(): getMethods() can only access methods declared as public in the class, and private methods cannot be accessed, and can access public methods inherited from other classes; getDeclaredMethods() can access all fields in the class, which has nothing to do with public, private, and protect, and cannot access methods inherited from other classes.
* The difference between getConstructors() and getDeclaredConstructors(): getConstructors() can only access constructors declared as public in the class; getDeclaredConstructors() can access all constructors in the class, and has nothing to do with public, private, and protect.
Get and modify the information of the array through reflection
int[] temp={1,2,3,4,5};Class<?> demo = temp.getClass().getComponentType();System.out.println("Array type: "+demo.getName());//intSystem.out.println("Array length: "+Array.getLength(temp));//5System.out.println("The first element of the array: "+Array.get(temp, 0));//1Array.set(temp, 0, 100);System.out.println("The first element of the array after modification is: "+Array.get(temp, 0));//100 Get the array typecls.getComponentType();Determine whether it is an array type
cls.isArray();
2 Java Agent
The proxy model is a commonly used Java design model. Its characteristic is that the proxy class and the delegate class have the same interface. The proxy class is mainly responsible for preprocessing messages, filtering messages, forwarding messages to the delegate class, and processing messages after the event. There is usually an association between the proxy class and the delegate class. The object of a proxy class is associated with the object of a delegate class. The object of the proxy class itself does not truly implement the service, but provides specific services by calling the relevant methods of the delegate class object.
According to the period of agent creation, agent classes can be divided into two types.
• Static proxy: Created by programmers or automatically generates source code by specific tools and then compiles it. Before the program runs, the .class file of the proxy class already exists.
•Dynamic proxy: When the program is running, bytecode is dynamically generated by the Java reflection mechanism.
2.1 Static proxy
public interface Count { public void queryCount();}public class CountImpl implements Count { public void queryCount() { System.out.println("View account method..."); }}//Proxy class public class CountProxy implements Count { private CountImpl countImpl; public CountProxy(CountImpl countImpl) { this.countImpl = countImpl; } @Override public void queryCount() { System.out.println("before transaction processing"); countImpl.queryCount(); // Call the delegate class method; System.out.println("after transaction processing"); }} // Test class public class TestCount { public static void main(String[] args) { CountImpl countImpl = new CountImpl(); CountProxy countProxy = new CountProxy(countImpl); countProxy.queryCount(); } }Observe the code and find that each proxy class can only serve one interface, so that too many proxy will inevitably occur in program development. Moreover, all proxy operations except for the different methods of calling, all other operations are the same, so the code must be repeated at this time. The best way to solve this problem is to complete all the proxy functions through a proxy class, so it must be done using dynamic proxy at this time.
2.2 Dynamic Agent
The bytecode of the dynamic proxy class is dynamically generated by the Java reflection mechanism when the program is run, without the need for programmers to write its source code manually. Dynamic proxy classes not only simplify programming but also improve the scalability of software systems, because the Java reflection mechanism can generate any type of dynamic proxy classes.
2.2.1 JDK dynamic proxy
The Proxy class and InvocationHandler interfaces 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 object being proxyed.
Method method: The method to be called
Object[] args: The parameters required when calling the method
You can think of a subclass of the InvocationHandler interface as the final operation class of a proxy, replacing ProxySubject.
Proxy class:
The Proxy class is an operation class that specializes in the proxy. It can dynamically generate implementation classes for one or more interfaces through this class. This class provides the following operation methods:
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException
Parameter description:
ClassLoader loader: class loader
Class<?>[] interfaces: Get all 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 complete the specific operation of the proxy.
interface Subject { public String says(String name, int age);}class RealSubject implements Subject { @Override public String says(String name, int age) { return name + " " + age; }}//JDK dynamic proxy class MyInvocationHandler implements InvocationHandler { private Object target = null; //Bind the delegate object and return a proxy class public Object bind(Object target) { this. target = target; return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); //Bind the interface (cglib makes up for this) } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before method!"); Object temp = method.invoke(target, args); System.out.println("after method!"); return temp; }}class hello { public static void main(String[] args) { MyInvocationHandler demo = new MyInvocationHandler(); Subject sub = (Subject) demo.bind(new RealSubject()); String info = sub.say("Rollen", 20); System.out.println(info); }} However, JDK's dynamic proxy relies on interface implementation. If some classes do not implement interfaces, they cannot use JDK proxy, so they need to use cglib dynamic proxy.
2.2.2 CGLIB dynamic proxy
The dynamic proxy mechanism of JDK can only proxy classes that implement interfaces, while classes that do not implement interfaces cannot implement JDK's dynamic proxy.
cglib implements proxy for classes. Its principle is to generate a subclass for the specified target class and override the method implementation enhancement. However, because inheritance is used, the final modified class cannot be proxyed.
public interface BookFacade { public void addBook(); } public class BookFacadeImpl1 { public void addBook() { System.out.println("Ordinary method to add books..."); } } import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; //cglib dynamic proxy class public class BookFacadeCglib implements MethodInterceptor { private Object target; //Bind the delegate object and return a proxy class public Object getInstance(Object target) { this.target = target; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.target.getClass()); // Callback method enhancer.setCallback(this); // Create proxy object return enhancer.create(); } @Override // Callback method public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println("Function start"); Object temp = proxy.invokeSuper(obj, args); System.out.println("Function end"); return temp; } } public class TestCglib { public static void main(String[] args) { BookFacadeCglib cglib = new BookFacadeCglib(); BookFacadeImpl1 bookCglib = (BookFacadeImpl1)cglib.getInstance(new BookFacadeImpl1()); bookCglib.addBook(); } }The above brief discussion on Java reflection and proxy is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.