Service接口
package spring.aop.DynamicProxy;
/**
* Created with IDEA
* author:liuhaotian
* Date:2019/9/1 23:03
* Description:
*/
public interface Service {
String sellCar(String carName);
}
Service实现类
package spring.aop.DynamicProxy;
/**
* Created with IDEA
* author:liuhaotian
* Date:2019/9/1 23:04
* Description:
*/
public class ServiceImpl implements Service{
@Override
public String sellCar(String carName) {
return carName + " is ready";
}
}
InvocationHandler 实现类
package spring.aop.DynamicProxy;
import basic.MyInterface;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* Created with IDEA
* author:liuhaotian
* Date:2019/9/1 23:05
* Description:
*/
public class MyInvocationHandler implements InvocationHandler {
private Object target;
//在构造函数中初始化target对象
public MyInvocationHandler(Object target) {
this.target = target;
}
/**
* 通过invoke方法调用target对象中的方法
*
* @param method
* @param args
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxyService, Method method, Object[] args) throws Throwable {
System.out.println("要执行的方法:" + method.getName());
//通过 method 的 invoke 方法调用 target 类中的方法
//!!!!! method(对象,入参)要用目标真实对象
Object result = method.invoke(target, args);
System.out.println("method.getName() 执行结果:" + result.toString());
return result;
}
}
测试类
package spring.aop.DynamicProxy;
import org.junit.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
* Created with IDEA
* author:liuhaotian
* Date:2019/9/1 23:11
* Description:
*/
public class DynamicProxyTest {
@Test
public void test(){
//要被代理的真实对象
Service service = new ServiceImpl();
//将真实对象交给代理
InvocationHandler invocationHandler = new MyInvocationHandler(service);
//创建代理对象
Service proxyService = (Service)Proxy.newProxyInstance(service.getClass().getClassLoader(),
service.getClass().getInterfaces(),invocationHandler);
System.out.println(proxyService.sellCar("BMM"));
}
}
输出结果:
要执行的方法:sellCar
method.getName() 执行结果:BMM is ready
BMM is ready