|
Import java. lang. reflect. InvocationHandler;
Import java. lang. reflect. Method;
Import java. lang. reflect. Proxy;
// Interface to be implemented by the proxy
Interface IVehical {
// For example, I have written two interfaces here.
Void run ();
Void say ();
}
// Concrete implementation
Class Car implements IVehical {
// The following two methods are used as the implementation methods of the interface. If these methods are not available in the interface, a redundant method program will not be compiled here.
// Each call to these two methods triggers the invoke method in the proxy object.
Public void run (){
System. out. println ("Car is running ");
}
Public void say ()
{
System. out. println ("just one! ");
}
}
// Proxy class
// This class is used to create a proxy object. It is simply encapsulated here.
Class VehicalProxy {
Private IVehical vehical;
Public VehicalProxy (IVehical vehical ){
This. vehical = vehical;
}
// This method returns the created object proxy.
Public IVehical create (){
Final Class <?> [] Interfaces = new Class [] {IVehical. class };
Final VehicalInvacationHandler handler = new VehicalInvacationHandler (vehical );
Return (IVehical) Proxy. newProxyInstance (IVehical. class. getClassLoader (), interfaces, (InvocationHandler) handler );
}
// This is a processor bound to the proxy object. Every time www.111cn.net calls a method in the object proxy, the invoke method in this processor is triggered.
Class VehicalInvacationHandler implements InvocationHandler {
Private final IVehical vehical;
Public VehicalInvacationHandler (IVehical vehical ){
This. vehical = vehical;
}
// Every time the say or call of the object proxy is executed (as long as it is a method in the IVehical interface), the invoke will be executed
Public Object invoke (Object proxy, Method method, Object [] args)
Throws Throwable {
System. out. println ("-- before running ...");
Object ret = method. invoke (vehical, args );
System. out. println ("-- after running ...");
Return ret;
}
}
}
Class Main {
Public static void main (String [] args ){
IVehical car = new Car ();
VehicalProxy proxy = new VehicalProxy (car );
IVehical proxyObj = proxy. create ();
ProxyObj. say ();
}
} |