The principle of dynamic proxies

1, 2 define an interface, the definition of a class that implements the interface 3, the use of proxy objects to obtain a dynamic method, and a method to enhance the solid object by three different methods (enhanced parameters, return value enhancement, body enhancement method) 
cn.hopetesting.proxy Package ;

/ **
* @author newcityman
* @date 2019/9/13 - 15:22
* /
public interface SaleComputer {
public String Sale ( Double Money) ;
public void Show () ;
}

cn.hopetesting.proxy Package ; 

/ **
* @author newcityman
* @date 2019/9/13 - 15:24
* /
public class Lenovo the implements SaleComputer {

@Override public String Sale ( Double Money) { the System. Out.println ( "It took" + Money + "yuan to buy a Lenovo computer .....") ; return "Lenovo" ; } @Override public void Show () { System. out.println ( "show off computer") ; } }












cn.hopetesting.proxy Package ; 

Import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer ;

Import java.lang.reflect.InvocationHandler ;
Import the java.lang.reflect.Method ;
Import the java.lang.reflect.Proxy ;

/ **
* @author newcityman
* @date 2019/9/13 - 15:34
* /
public class ProxyTest {
public static void main (String [] args) {
//. 1, to create a real object
Lenovo Lenovo = new new Lenovo ( ) ; // 2, Lenovo enhanced dynamic proxy objects / * * three parameters * 1, class loader: the real object .getClass () getClassLoader (). * 2, an array of interfaces: the real object .getClass () getInterfaces ().





* 3, the processor: of InvocationHandler new new ()
* * /
. SaleComputer proxy_lenovo = (SaleComputer) the Proxy 'newProxyInstance (lenovo.getClass () getClassLoader (). , Lenovo.getClass () The getInterfaces (). , Of InvocationHandler new new () {
/ * *
*
* @param proxy proxy object
* @param method the method of the proxy object called, is encapsulated as an object
* @param args when the strip method with the proxy object, the actual parameters passed
* @return * @throws the Throwable * / @Override public Object Invoke (Object Proxy , Method, Method , Object [] args) throws the Throwable {




/*System.out.println ( "dynamic method is performed the proxy");
System.out.println (method.getName ());
System.out.println (args [0]); * / IF (Method. . getName () the equals ( "Sale") ) { //. 1, enhancement parameters Double Money = ( Double) args [ 0] ; Money Money * = 0.85 ; . the System Out.println ( "pick car") ; // use The real object calls the method String obj = (String) Method.invoke ( lenovo , Money) ; System. out.println ( "free shipping .....") ; // return value enhancement obj = obj + "_ removable hard disk " ; return obj ; } the else { Object obj = Method.invoke(













lenovo, args);
return obj;
}
}
});

//2、调用方法
String computer = proxy_lenovo.sale(5000);
System.out.println(computer);

/* proxy_lenovo.show();*/


}
}
 

Guess you like

Origin www.cnblogs.com/newcityboy/p/11517237.html