一、静态代理
二、动态代理
动态代理通过java.lang.reflect包中Proxy类和InvocationHandler接口实现。即通过java的反射机制实现动态的创建代理类,通过调用代理类的方法来实现调用目标对象的方法。
概念:
代理类:所有的代理类都是
Proxy的子类。
目标类:被代理的类。target。
必须实现接口。
生成代理工具类:
InvocationHandler实现类。
目标类不实现接口的现象:
People people = new People();
People obj =(People) proxyFun.newInstance(people);
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to proxy.domain.People
interface Subject接口:
package proxy.domain; /** * Created by guofeipeng on 15/10/29. */
public interface Subject {
public void say();
}
People.java
package proxy.domain; /** * Created by guofeipeng on 15/10/29. */
public class People implements Subject {
public void say() {
System.out.println("hello world!!!");
}
}
ProxyFun.java
package proxy.fun;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/** * Created by guofeipeng on 15/10/29. */
public class ProxyFun implements InvocationHandler {
private Object target;
public Object newInstance(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 {
Object obj = null;
System.out.println("=====before===");
obj = method.invoke(target,args); //注意,这里是method invoke执行的是target的method,不是proxy,不然会导致死循环,不知道InvocationHandler的invoke方法proxy参数干嘛用的。
System.out.println("=====before==="); return obj;
}
}
测试Demo
package proxy.fun;
import proxy.domain.People;
import proxy.domain.Subject;
/** * Created by guofeipeng on 15/10/29. */
public class Demo {
public static void main(String[] args) {
ProxyFun proxyFun = new ProxyFun();
Subject people = new People();
Subject obj = (Subject) proxyFun.newInstance(people);
System.out.println("代理类类型===》" + obj.getClass());
obj.say();
}
}