动态代理

由于使用静态代理的话,每新建一个新的service 类就要建一个对应的代理类,所以使用静态代理比较麻烦和繁琐,所以这里我们引入动态代理

1.新建studentService接口和他的实现类studentServiceImpl

//接口类
package service2;

public interface StudentService {
    public void add();
    public void del();
    public void select();
}

//实现类
package service2.impl;

import service2.StudentService;

public class StudentServiceImpl implements StudentService {
    public void add() {
        System.out.println("动态代理的add");
    }

    public void del() {
        System.out.println("动态代理的del");
    }

    public void select() {
        System.out.println("动态代理的select");
    }
}

 

2.新建动态代理类

package service2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//要实现这个接口InvocationHandler
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的接口
    private Object target;
    public void setTarget(Object target) {
        this.target = target;
    }
    //生成得到代理类
    public Object getProxy() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }

    //处理代理实例,并返回结果。注意:这里就是增强方法的地方
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        Object result=method.invoke(target,args);
        return result;
    }
    public void log(String msg){
        System.out.println("正在执行"+msg+"方法!");

    }
}

 

3.测试

package test;

import service2.ProxyInvocationHandler;
import service2.StudentService;
import service2.impl.StudentServiceImpl;

public class testProxy {
    public static void main(String[] args) {
        //被代理的对象,也就是真实的对象
        StudentServiceImpl studentImpl=new StudentServiceImpl();

        //获取代理对象
        ProxyInvocationHandler pih =new ProxyInvocationHandler();

        //让代理类代理真实的对象
        pih.setTarget(studentImpl);

        //动态生成代理类(这里用接口)
        StudentService studentProxy= (StudentService) pih.getProxy();
        studentProxy.add();
        studentProxy.del();
        studentProxy.select();
    }
}

 

package test;

import service2.ProxyInvocationHandler;
import service2.StudentService;
import service2.impl.StudentServiceImpl;

public class testProxy {
public static void main(String[] args) {
//被代理的对象,也就是真实的对象
StudentServiceImpl studentImpl=new StudentServiceImpl();

//获取代理对象
ProxyInvocationHandler pih =new ProxyInvocationHandler();

//让代理类代理真实的对象
pih.setTarget(studentImpl);

//动态生成代理类(这里用接口)
StudentService studentProxy= (StudentService) pih.getProxy();
studentProxy.add();
studentProxy.del();
studentProxy.select();
}
}
posted @ 2020-09-02 00:53  呆马and鸽子  阅读(85)  评论(0)    收藏  举报