小强哥博客

小强哥,小强哥博客,技术大咖

JDK动态代理以及CgLib动态代理实现

package com.eju;

public interface UserService {
    void process(String name,int age);
}
package com.eju;

public class UserServiceImpl implements UserService {
    @Override
    public void process(String name, int age) {
        System.out.println("name:"+name+",age:"+age);
    }
}

jdk动态代理

package com.eju;

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

public class ServiceHandler implements InvocationHandler{

    public ServiceHandler(){

    }

    private Object target;
    public ServiceHandler(Object target){
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>");
        Object result = method.invoke(target,args);
        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<");
        return result;
    }
}

jdk动态代理测试

package com.eju;

import java.lang.reflect.Proxy;

public class TestUserForJDKProxy {
    public static void main(String [] args){
        UserService userService = new UserServiceImpl();
        ServiceHandler serviceHandler = new ServiceHandler(userService);

        UserService proxy = (UserService) Proxy.newProxyInstance(
                userService.getClass().getClassLoader(),
                userService.getClass().getInterfaces(),
                serviceHandler
        );

        proxy.process("zhangsan",10);
    }
}


输出内容

>>>>>>>>>>>>>>>>>>>>>>>
name:zhangsan,age:11
<<<<<<<<<<<<<<<<<<<<<<<

cglib动态代理

package com.eju;

import org.mockito.cglib.proxy.Enhancer;
import org.mockito.cglib.proxy.MethodInterceptor;
import org.mockito.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor{

    private Enhancer enhancer = new Enhancer();

    public Object getProxy(Class clazz){
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>");
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<");
        return result;
    }
}

cglib动态代理测试

package com.eju;


public class TestUserForCglibProxy {
    public static void main(String [] args) {
        CglibProxy cglibProxy = new CglibProxy();
        UserServiceImpl userService = (UserServiceImpl) cglibProxy.getProxy(UserServiceImpl.class);
        userService.process("zhangsan", 11);
    }
}


输出内容

package com.eju;


public class TestUserForCglibProxy {
    public static void main(String [] args) {
        CglibProxy cglibProxy = new CglibProxy();
        UserServiceImpl userService = (UserServiceImpl) cglibProxy.getProxy(UserServiceImpl.class);
        userService.process("zhangsan", 11);
    }
}


完。