Proxy mode
Brief introduction:
Instead of manipulating the actual object directly, the actual object is manipulated indirectly through the proxy object, and the specific user does not know the specific
object or the actual object.
Static proxy
1. Example
1), by proxy class
Package Demo3;
public class AA {
public void Method () {
System.out.println ("ADFADF");
}
}
2), Agent class
public class BB {
Private Object AA;
Public BB (Object aa) {
Super ();
THIS.AA = AA;
}
Public Object Getaa () {
return AA;
}
}
3), test
Package Demo3;
public class Example {
public static void Main (string[] args) {
AA aa=new AA ();
bb bb=new bb (aa);
((AA) (Bb.getaa ())). method ();
}
}
The use of dynamic class Proxy in Java dynamic Agent---
1, the proxy class interface
Package Demo2;
Public interface IA {
public string method1 (string str,string str1);
public void method2 ();
}
2, by the agent class
Package Demo2;
public class A implements ia{
@Override
public string method1 (string str,string str1) {
SYSTEM.OUT.PRINTLN ("method1------" +str+ "------" +STR1);
return str1;
}
@Override
public void Method2 () {
System.out.println ("Method2");
}
}
3. Agent Class
Package Demo2;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
public class Handleproxya implements Invocationhandler {
Private IA ia;
Public Handleproxya (ia ia) {
Super ();
This.ia = IA;
}
/**
* @param proxy: Agent class
* @param method: proxy class methods
* @param args: List of method methods by proxy class
* @return return value is the return value of the proxy class method
*/
@Override
public object invoke (object proxy, Method method, object[] args)
Throws Throwable {
if (args!=null) {
for (int i = 0; i < args.length; i++) {
System.out.println (Args[i]);
}
}
Object result = Method.invoke (ia, args);
SYSTEM.OUT.PRINTLN (result);
return result;
}
}
4. Example
Package Demo2;
Import Java.lang.reflect.Proxy;
public class Example {
public static void Main (string[] args) {
IA ia=new A ();//being represented
Handleproxya Proxya=new Handleproxya (IA);//Agent
To create a dynamic proxy object
IA ia2 = (ia) proxy.newproxyinstance (Ia.getclass (). getClassLoader (), Ia.getclass (). Getinterfaces (), Proxya);
Ia2.method1 ("Asdfad", "245245");
IA2.METHOD2 ();
}
}
The use of dynamic class Proxy in Java dynamic Agent---