JDK动态代理Demo代码,进一步学习分析

 

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyHandler<T> implements InvocationHandler {

    private T target;

    public ProxyHandler(T target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("before invoke .");
        Object ret = method.invoke(target, args);
        System.out.println("after invoke .");
        return ret;
    }


    public T getProxy() {
        return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(), this);
    }
}

  

 

 

public interface UserService {

    String echo(String content);
}

  

 

import sun.misc.ProxyGenerator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class UserServiceImpl implements UserService {

    @Override
    public String echo(String content) {
        return content + "_impl";
    }


    public static void main(String[] args) throws IOException {

        UserService us = new UserServiceImpl();
        ProxyHandler<UserService> proxyHandler = new ProxyHandler<>(us);
        UserService userService = proxyHandler.getProxy();


        System.out.println(userService.echo("hello java "));
        System.out.println(userService.getClass());
        generateProxyClassToFile();


    }


    public static void generateProxyClassToFile() throws IOException {
        byte[] bts = ProxyGenerator.generateProxyClass("$Proxy0", new Class[]{UserService.class});
        File file = new File("./", "$Proxy0.class");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bts);
        fos.flush();
        fos.close();
    }
}

  

 

上一篇:Python编程:从入门到实践------第7章:用户输入和while循环


下一篇:《Python从入门到实践》第七章动手试一试