-
-
Role: to enhance the method does not modify the source code on the basis of
-
classification:
-
Dynamic agent interface
-
Based on a dynamic proxy class
-
-
Based on a dynamic proxy class:
-
Class involved: Enhance
-
Contributors: third-party libraries cglib
-
How to create a proxy object: use the create method Enhance class
-
Create a proxy object request: to be the agent class can not be the final class
-
create method parameters:
-
class: bytecode
It is loaded with the proxy object in the bytecode was written proxy object class loader. (Agent who will come to write the class loader)
-
Callback: code for providing enhanced
It is how we write the proxy. We are generally more a class that implements this interface, are usually anonymous inner classes, but not required. Class that implements this interface with who write. We generally write a sub-interface implementation class of this interface: MethodInterceptor
-
Package com.xuefei.cglibProxy; // manufacturer public class Producer { public void saleProduct ( a float Money) { System.out.println ( "the money, goods to you" + Money); } public void afterProduct ( a float Money) { System.out.println ( "you get the money sale" + Money); } }
package com.xuefei.cglibProxy; import com.xuefei.proxy.IProducer; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class Client { public static void main(final String[] args) { final Producer producer = new Producer(); Producer producer1 = (Producer) Enhancer.create (producer.getClass (), new new MethodInterceptor () { / ** * performing any incorporated methods are proxied through the object's method * @param Proxy * @param Method * @param args * @param methodProxy * @return * @throws the Throwable * / public Object Intercept (Object Proxy, Method, Method, Object [] args, methodProxy methodProxy) throws the Throwable { // provide enhanced code The returnValue = Object null ; // acquisition parameters the method performed the Float Money = (the Float) args [0 ]; // determines whether the current method is not sold IF ( "saleProduct" .equals (method.getName ())) { the returnValue = Method .invoke (Producer, Money * 0.8 F ); } return the returnValue; } }); producer1.saleProduct (1000f); } }
-
-
Dynamic agent (based dynamic proxy class)
Guess you like
Origin www.cnblogs.com/lililixuefei/p/11906204.html
Recommended
Ranking