黑马程序员技术交流社区
标题:
动态代理的一点小问题
[打印本页]
作者:
朱玉玺
时间:
2013-1-30 00:38
标题:
动态代理的一点小问题
本帖最后由 朱玉玺 于 2013-1-30 00:50 编辑
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
interface Advice {
void beforeMethod(Method method);
void afterMethod(Method method);
}
class MyAdvice implements Advice {
long startTime=0;
@Override
public void beforeMethod(Method method) {
System.out.println("方法开始啦");
startTime = System.currentTimeMillis();
}
@Override
public void afterMethod(Method method) {
System.out.println("方法结束啦");
long endTime = System.currentTimeMillis();
System.out.println(method.getName()+" running time:"+(endTime - startTime));
}
}
public class ProxyTest {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
final ArrayList target = new ArrayList();
Collection proxy =(Collection) getProxy(target,new MyAdvice());
// ArrayList it =(ArrayList) getProxy(target,new MyAdvice()); 这句报错
List proxy1 =(List) getProxy(new ArrayList(),new MyAdvice());
Iterable it = (Iterable)getProxy(new ArrayList(),new MyAdvice());
/*
我的问题:1.这里的getProxy()方法传递的参数是final类型的,但为什么我传入new ArrayList()没有定义成final,没有定义成final也通过编译而且运行正常?
2.这里的代理设计模式,跟装饰设计模式很类似,都是传入一个类,然后返回一个新类,同时多了一些功能,这两个设计模式有什么区别?
3.Collection 能指向这个代理类,说明这个代理类是Collection的一个实现类,但也没有标记implement怎么就实现了?
将其强转为ArrayList编译失败,说明它是不是ArrayList或者其子类,它跟ArrayList的最大公约数是什么?
*/
// System.out.println("iterable:"+it.iterator());
proxy1.add("lisi");
proxy.add("wangwu");
System.out.println(proxy.size());
}
public static Object getProxy(final Object target,final Advice advice) {
Object proxy3 =Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforeMethod(method);
Object retVal = method.invoke(target, args);
advice.afterMethod(method);
return retVal;
}
});
return proxy3;
}
}
复制代码
作者:
梁俊
时间:
2013-1-30 08:54
内部类调用外部类变量才需要final
作者:
孙金鑫
时间:
2013-6-20 01:35
问题1、你传进去的是具体的对象,不需要类型修饰控制,所以不需要final Object object的啥东西了。
问题2、装饰设计模式与代理模式,看起来的确很相似,都有实现一个接口,都有添加功能的作用。但装饰设计模式主要关注于添加某些方法。代理模式,主要用于控制,你完全可以更改从目标(target)到客户端(client)的数据,这就是代理。
问题3、static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
返回一个指定接口的代理类实例,该接口可以将方法调用指派到指定的调用处理程序。
这里是一个接口数组!返回:一个指定接口的代理类实例。(我只能这么理解。。。。)
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2