What are reflection and dynamic proxies?

Reflection is an introspection capability provided by Java to create instances of classes, access member variables, and methods at run time.

A dynamic proxy is a dynamic proxy object that a program builds at run time.

Reflection and dynamic proxies are the basis for encapsulation by third-party frameworks.

reflection

An introspection provided by a program to manipulate classes and objects at run time.

The core classes provided are as follows:

Class: Gets the definition of a Class

Field: Gets the declared property

Method: The Method to obtain the claim

Constructor: Constructs a new object

Note the setAccessble (Boolean) method;

You can modify the access control permissions of related objects reflected;

Such as:

ORM framework automatically generates set and GET methods; Some API private member and method operation, custom API function;

A dynamic proxy

The runtime automatically builds the proxy to handle method calls;

The implementation methods are: jdkProxy, Cglib;

Compare the project instructions
JdkProxy 1. Simple code

2. No additional dependencies

3, you can follow the JDK smooth upgrade
Cglib 1, excellent performance

2. Do not implement additional interfaces

3. Only care about the class of the operation

Common applications: RPC calls, AOP

The following code is an example of using jdkProxy:

public class MyDynamicProxy { public static void main (String[] args) { HelloImpl hello = new HelloImpl(); MyInvocationHandler handler = new MyInvocationHandler(hello); / / structure code examples Hello proxyHello = (Hello) Proxy. NewProxyInstance (HelloImpl. Class. GetClassLoader (), HelloImpl.class.getInterfaces(), handler); // Invoke the proxy method proxyhello.sayHello (); } } interface Hello { void sayHello(); } class HelloImpl implements Hello { @Override public void sayHello() { System.out.println("Hello World"); } } class MyInvocationHandler implements InvocationHandler { private Object target; public MyInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Invoking sayHello"); Object result = method.invoke(target, args); return result; }}Copy the code

Use of AOP:

summary

This section covers the details of reflective, dynamic proxies. And common application scenarios.

Original is not easy, reprint please indicate the source.