- 目的:完成代码的增强
- 个人理解:代理类在程序运行时创建的代理方式被成为动态代理。 我们上面静态代理的例子中,代理类(studentProxy)是自己定义好的,在程序运行之前就已经编译完成。然而动态代理,代理类并不是在Java代码中定义的,而是在运行时根据我们在Java代码中的“指示”动态生成的。相比于静态代理, 动态代理的优势在于可以很方便的对代理类的函数进行统一的处理,而不用修改每个代理类中的方法。
- 接口类
package com.gaoji.member;
public interface Person {
void showName();
void showAge();
void showSex();
}
package com.gaoji.member;
public class PersonImpl implements Person{
@Override
public void showName() {
System.out.println("我叫张三");
}
@Override
public void showAge() {
System.out.println("今年十八岁");
}
@Override
public void showSex() {
System.out.println("我是男孩子");
}
}
package com.gaoji.member;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;
public class InvocationHandlerImpl implements InvocationHandler{
private Object target;
public InvocationHandlerImpl(Object target) {
super();
this.target = target;
}
public Object getProxy() {
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method.getName()+"开始"+new Date());
Object result = method.invoke(target, args);
System.out.println(method.getName()+"结束了"+new Date());
return result;
}
}
package com.gaoji.member;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MainTest {
public static void main(String[] args) {
Person p=new PersonImpl();
InvocationHandlerImpl handler =new InvocationHandlerImpl(p);
Person p1=(Person) handler.getProxy();
p1.showAge();
p1.showName();
p1.showSex();
}
}
showAge开始Fri May 10 21:04:34 GMT+08:00 2019
今年十八岁
showAge结束了Fri May 10 21:04:34 GMT+08:00 2019
showName开始Fri May 10 21:04:34 GMT+08:00 2019
我叫张三
showName结束了Fri May 10 21:04:34 GMT+08:00 2019
showSex开始Fri May 10 21:04:34 GMT+08:00 2019
我是男孩子
showSex结束了Fri May 10 21:04:34 GMT+08:00 2019