1.静态代理
需要接口、代理类、被代理类
通过代理类来创建实例,完成调用,这里会用到多态(父类的引用指向子类的对象)
例:接口
public interface ProxyApi {
void Study(String name);
}
被代理类:
public class ProxyTestImpl implements ProxyApi {
@Override
public void Study(String name) {
System.out.println(name);
}
}
代理类:
ProxyApi p = new ProxyTestImpl();
p.study("AAA");
2.动态代理
- 不用编写实现类,JVM运行时创建接口对象。
- 通过调用Proxy.newProxyInstance创建运行时的对象,需要传入三个参数:
(1)接口类的ClassLoader
(2)接口数组(最少有一个)
(3)InvocationHandler 对象 - 通过InvocationHandler 实例来实现接口方法的调用
public class ProxyHandler{
public static void main(String[] args) {
System.out.println("aaaaaaaa");
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method);
if (method.getName().equals("Study")) {
System.out.println(args[0]+"\tlike english");
}
return null;
}
};
ProxyApi proxyTest = (ProxyApi) Proxy.newProxyInstance(
ProxyTest.class.getClassLoader(),
new Class[]{ProxyApi.class},
handler);
proxyTest.Study("zhangsan");
}
}