如何使用动态代理,如何使用呢?

如何使用动态代理,如何使用呢?

我先创建一个动态代理类


public class ProxyUser implements InvocationHandler {
private Object target;

public Object bind(Object target) {
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if("getNames".equals(method.getName()))
System.out.println("getNames is invocations");
return method.invoke(target, args);
}
}
然后我们再创建一个接口(为什么要创建接口?原因是动态代理只能代理一个实现了一个或多个接口的类)


public interface UserInterface {
public String getNames();

}
现在再创建一个实现类: tkyhyl96.com bossyl21.com wlgjyl55.com bjdylc32.com amnylc49.com


public class UserImpl implements UserInterface{
@Override
public String getNames() {
return "Leo";
}
}
一切准备就绪,现在开始调用了

?
1
2
3
4
5
public static void main(String[] args) {
ProxyUser proxyuser=new ProxyUser();
UserInterface user= (UserInterface) proxyuser.bind(new UserImpl());
System.out.println(user.getNames());
}
运行一下结果:

getNames is invocations
Leo


return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
这里是动态代理的关键,为什么要使用类加载器?原因:动态代理是在内存中动态生成一个并被加载到方法区,要加载就需要类加载器!

那为什么要使用系统类加载器?使用不同的类加载器涉及一个命名空间的问题,命名空间不同会导致无法调用,又是一个类加载方面的问题,后面我们再着重讨论下。

从上面这段代理我们可以看出动态代理的限制:被代理的类必须要实现一个或者多个接口,但是如果我们代理的类本身就是一个接口或者没有实现接口呢?

这个就要通过CGLIB来代理了,下一节就讲cglib。

posted on 2014-03-18 14:57  有木有格子  阅读(840)  评论(0编辑  收藏  举报