代理就是,就是将对象的控制权交给第三方,可以用来增强功能,两种方式,静态与动态,所谓的静态就是只能代理一种类对象(如果到父类这一层,可以当作同一类哈),动态的话是可以代理多个类型的对象。
静态代理,实际上是是在代理处通过对象的方式调用函数。
package AOP;
public class ProxyServiceA implements IService {
public ProxyServiceA(IService service) {
super();
this.service = service;
}
//代理对象
private IService service;
public void service(String name) throws Exception {
System.out.println("log start");
try{
//通过对象本身调用函数或者叫做方法
service.service(name);
}
catch(Exception e)
{
throw e;
}
System.out.println("log end");
}
public static void main(String[] args) throws Exception {
IService service=new ServiceImplA();
service =new ProxyServiceA(service);
service.service("CYW");
}
}
动态代理的话,就是生成动态代理对象了,已经不使用对象本身了。生成代理对象之后,就是使用
package AOP;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynaProxyServiceA implements InvocationHandler {
private Object target;//目标对象
public Object bind(Object object){
this.target = object;
//生成动态代理对象
Object obj=Proxy.newProxyInstance(this.target.getClass().getClassLoader(), this.target.getClass().getInterfaces(), this);
return obj;
}
//方法调用实现
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
System.out.println(proxy.getClass().getName());
System.out.println("method:"+method);
System.out.println("args:"+args);
System.out.println("target:"+this.target);
System.out.println("log start");
try{
//方法调用实现,此处为调用处
result = method.invoke(this.target, args);
}
catch(Exception e)
{
throw e;
}
System.out.println("log end");
return proxy;
}
public static void main(String[] args) throws Exception {
IService service = (IService) new DynaProxyServiceA().bind(new ServiceImplA());
service.service("CYW");
}
}
package AOP;
public interface IService {
public void service(String name) throws Exception;
}
package AOP;
public interface ITest {
public void test(String name) throws Exception;
}
package AOP;
public class ServiceImplA implements IService,ITest {
@Override
public void service(String name) throws Exception {
System.out.println("ServiceImplA service:"+name);
}
@Override
public void test(String name) throws Exception {
System.out.println("ServiceImplA test:"+name);
}
}