最近学习了一下动态代理,感觉很有意思,就简单学习了一下,动态代理的思路比较简单。
动态代理:顾名思义,就是为了能够对某个类进行代理,为什么要就行代理呢?在某些时候,我们希望在不改变原始类的方法的情况下,能够在方法的前面和后面,添加诸如:运行时间,添加日志等等,这个时候就要使用动态代理了。
好了,废话不多说,上代码。
//接口
pubic interface HelloWorldImpl{
void printHelloWorld();
}
//实现这个接口的类
public class HelloWorld implements HelloWorldImpl{
@Override
public void printHelloWorld(){
System.out.println("Hello World! ");
}
}
//对这个接口的动态代理
public class HelloWorldHandler implements InvocationHandler{
private Object target;
public HelloWorldHandler(Object target){
this.target=target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object o=null;
System.out.println("Before method");
/*此处使用的是java的反射机制
*相当于target.method();
*/
o=method.invoke(target, args);
System.out.println("After method");
return o;
}
}
public static void main(String[] args){
HelloWorldImpl helloWorld=new HelloWorld();
InvocationHandler handler=new HelloWorldHandler(helloWorld);
HelloWorldImpl proxy=(HelloWorldImpl) Proxy.newProxyInstance(helloWorld.getClass().getClassLoader(), helloWorld.getClass().getInterfaces(), handler);
proxy.printHelloWWorld();
}
运行结果是: