JDK dynamic proxy (1) and jdk dynamic proxy

Source: Internet
Author: User

JDK dynamic proxy (1) and jdk dynamic proxy

1. What is proxy?
Proxy, that is, to complete some additional tasks in place of the main character. For example, stars all have brokers. Before the stars participate in a movie, The brokers, as agent of the stars, negotiate with the funders about pay-as-you-go and schedule. The stars who actually participate in the film are the stars themselves, the agent stars are used to clear credits. The proxy mechanism in Java is to execute some additional operations before and after the execution of the target method, such as security check and logging. The proxies in Java are divided into static proxies and dynamic proxies.

2. Static proxy
First, let's take a look at the static proxy and directly go to the Code. The Code simulates the login operation.

public interface LoginService {    void login();}public class LoginServiceImpl implements LoginService {    @Override    public void login() {        System.out.println("login");    }}public class LoginServiceProxy implements LoginService {    private LoginService loginService;    public LoginServiceProxy(LoginService loginService) {        this.loginService = loginService;    }    @Override    public void login() {        beforeLogin();        loginService.login();        afterLogin();    }    private void beforeLogin() {        System.out.println("before login");    }    private void afterLogin() {        System.out.println("after login");    }}public class Client {    @Test    public void test() {        LoginService loginService = new LoginServiceImpl();        LoginService loginServiceProxy = new LoginServiceProxy(loginService);        loginServiceProxy.login();    }}

The output result is as follows:

before loginloginafter login

The static proxy implemented in the above Code is easy to understand. The aggregation method is used to perform additional operations before and after logon. You can see the code of a specific proxy class in the static proxy mode, and the code is compiled by the programmer. After compilation, the corresponding class file is generated. Disadvantages of using static Proxy: If you need to proxy all methods in the LoginService interface, you need to create N proxy methods in the proxy class and write repeated proxy operation code.

3. Concepts
The target interface, that is, the abstraction of the target operation, such as LoginService.
The target class, that is, the implementation class of the Target Interface, such as LoginServiceImpl.
The target object, that is, the instance of the target class.
Proxy class, that is, the proxy of the target class, such as LoginServiceProxy.
Proxy object, that is, the instance of the proxy class.

4. Dynamic proxy
Dynamic Proxy: the proxy class dynamically generated according to the target interface at runtime. The dynamic proxy method does not generate the actual class file after compilation. Instead, it dynamically generates class bytecode at runtime and loads it into JVM for use. The following code uses the dynamic proxy mechanism of JDK to simulate logon operations.

public interface LoginService {    void login();}public class LoginServiceImpl implements LoginService {    @Override    public void login() {        System.out.println("login");    }}public class ProxyInvocationHandler implements InvocationHandler {    private LoginService loginService;    public ProxyInvocationHandler(LoginService loginService) {        this.loginService = loginService;    }    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        beforeLogin();        Object invokeResult = method.invoke(loginService, args);        afterLogin();        return invokeResult;    }    private void beforeLogin() {        System.out.println("before login");    }    private void afterLogin() {        System.out.println("after login");    }}public class Client {    @Test    public void test() {        LoginService loginService = new LoginServiceImpl();        ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler(loginService);        LoginService loginServiceProxy = (LoginService) Proxy.newProxyInstance(loginService.getClass().getClassLoader(), loginService.getClass().getInterfaces(), proxyInvocationHandler);        loginServiceProxy.login();        createProxyClassFile();    }    public static void createProxyClassFile() {        String name = "LoginServiceProxy";        byte[] data = ProxyGenerator.generateProxyClass(name, new Class[]{LoginService.class});        try {            FileOutputStream out = new FileOutputStream("/Users/" + name + ".class");            out.write(data);            out.close();        } catch (Exception e) {            e.printStackTrace();        }    }}

The output result is as follows.

before loginloginafter login

Follow these steps:
1. Write the target interface;
2. Write the target class to implement the specific logic of the target method;
3. Compile a proxy processor class to implement the InvocationHandler interface, and rewrite the invoke method to specify the specific operations that will be completed by the generated proxy class during runtime, including beforeLogin and afterLogin. The invoke method is called when a proxy object calls any proxy method;
4. Create a proxy object and call the proxy method using the proxy object.

The above steps mainly involve the following two classes: java. lang. reflect. InvocationHandler and java. lang. reflect. Proxy.InvocationHandler is an interface called processor of the proxy class. Each proxy object has an associated call processor, which is used to specify the specific operations to be completed by the dynamically generated proxy class. This interface has an invoke method. When a proxy object calls a method of any target interface, this invoke method is called. In this method, the target method of the target class is called.Proxy provides static methods for creating dynamic Proxy classes and Proxy class instances. At the same time, the Proxy class created using the methods provided by Proxy is its subclass. This class focuses on the newProxyInstance method, which is used to create proxy class objects. The method declaration is as follows:

public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)

The loader parameter is used to indicate which class loader is used to load the proxy class. interfaces indicates the list of interfaces implemented by the proxy class, and h indicates the call processor used.

In subsequent articles, "go deep into JDK dynamic proxy (ii)" will go deep into the source code to analyze what kind of proxy class is generated by JDK dynamic proxy. Why do I always call the invoke method when calling any method of the proxy class, it is worth looking forward!

  

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.