Java动态代理举例:
Java源代码:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//提供服务的接口
interface Service
{
public String sellCar(String carName);
}
//实现服务的类
class ServiceTmpl implements Service{
@Override
public String sellCar(String carName)
{return carName + " is ready!";}
}
class MyInocationHandler implements InvocationHandler {
private Object target;
MyInocationHandler(Object target)
{this.target = target;}
@Override
public Object invoke(Object o, Method method, Object[] args) throws Throwable{
System.out.println("Call:" + method.getName());
Object result = method.invoke(target,args);
return result;
}
}
public class DynamicProxy {
public static void main(String[] args){
Service service = new ServiceTmpl();
InvocationHandler invocationHandler = new MyInocationHandler(service);
Service serviceProxy = (Service)
Proxy.newProxyInstance(service.getClass().getClassLoader(),service.getClass().getInterfaces(),invocationHandler);
System.out.println(serviceProxy.sellCar("Aston Martin"));
}
}