动态代理
代理的作用就是控制对象的访问权限;
首先我们需要写一个接口 这个就是代理接口
public interface Student {
public void S1();
}
然后在写一个接口的实现类 这个是原类
package proxytest;
public class StudentImpl implements Student {
private String name;
public StudentImpl() {
};
public StudentImpl(String name) {
this.name = name;
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void holler() {
System.out.println("holler ");
}
public void S1() {
this.holler();
System.out.println("我是S1");
}
}
我们还需要写一个生成代理对象的工厂
package proxytest;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyFactory implements InvocationHandler {
private Object object = null;
public Object getp(Object object) {
this.object = object;
return Proxy.newProxyInstance(
this.object.getClass().getClassLoader(),
this.object.getClass().getInterfaces(),
this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
StudentImpl si = (StudentImpl) this.object;
Object o = null;
if (si.getName() != null) {
o = method.invoke(this.object, args);
StudentImpl ss = (StudentImpl)o;
System.out.println(ss.getName());
}else{
System.out.println("你的权限不足。");
}
return o;
}
}
在这个工厂里面调用 proxy 的构造方法 newProxyInstance 传入相关参数 会返回一个对应的代理对象
我们可以看一下里面的源码
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
if (h == null) {
throw new NullPointerException();
}
Class<?> cl = getProxyClass0(loader, interfaces);
try {
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
SecurityManager sm = System.getSecurityManager();
if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) {
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
return newInstance(cons, ih);
}
});
} else {
return newInstance(cons, ih);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString());
}
}
在这个方法返回的时候又调用了 newInstance,显然这个方法是做创建代理对象的
最后在写一个代理的测试类
package proxytest;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
Student student = new StudentImpl("ss");
ProxyFactory pt = new ProxyFactory();
Student pro = (StudentImpl)pt.getp(student);
pro.S1();
}
}
输出结果:
holler
我是S1
总结
动态代理是在静态代理的基础上进行优化和补充,实现的步骤为
1.编写一个代理接口
2.编写一个接口实现类
3.编写一个代理的的创建工厂
4.测试类。调用工厂传入需要代理的对象
动态代理是在程序员需要时,程序会根据jdk的反射机制对需要的代理类进行加载, 这是动态代理的最大特点,虽然
这点在小程序里面的不到体现,但是在加载大文件时,差异就很明显了, 动态代理中利用了java中的 proxy 类
这是一个创建代理对象的类,上面我们用到了他的构造方法,其内部就是对代理类的加载 预编译的实现过程;
静态代理模式会在程序运行之前,先把代理对象编译成class文件,这是静态代理和动态代理的根本区别
在spring中就有代理这个功能,其实现原理也是相同的,spring中在对象上加上注解或重写其set方法就可以了;