JdkProxy

package com.albert.spring.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class JdkProxy implements InvocationHandler
{
    private Object target;
    
    public Object createTarget(Object target)
    {
        
        this.target = target;
        /****
         * 参数
         * 1.目标对象的类装载器 
         * 2目标对象的接口 
         * 3回调对象 
         * 生成的代理对象要执行方法时就是依靠这个回调对象的invoke方法来进行目标对象的方法回调
         */
        return Proxy.newProxyInstance(this.target.getClass().getClassLoader(),
            this.target.getClass().getInterfaces(),
            this);
    }
    
    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable
    {
        StudentDaoImpl udi = (StudentDaoImpl)target;
        Object result = null;
        if (udi.getName() != null)
        {
            result = method.invoke(target, args);
        }
        else
        {
            System.out.println("name is null, can't add stduent ");
        }
        return result;
    }
    
    public static void main(String[] args)
    {
        JdkProxy jdk = new JdkProxy();
        /****
         * JDK的Proxy实现代理要求被代理的目标对象必须实现一个接口,
         * 而如果目标对象没有实现接口则不能使用Proxy来代理
         */
        StudentDao<Student> studentDaoImpl = (StudentDao<Student>)jdk.createTarget(new StudentDaoImpl());
        studentDaoImpl.addStudent();
    }
}

你可能感兴趣的:(java,spring,jdk)