Dynamic Proxy Case 1: use proxy dynamic Proxy to enhance the method. Use Case proxy
Dynamic proxy Case 1:
/* Requirement: use Proxy dynamic Proxy to enhance the Method
Question:
1. Define the interface Fruit with the addFruit Method
2. Define implementation class FruitImpl to implement the Fruit Interface
3. Define the test class and use the dynamic proxy class to enhance the addFruit Method */
1 import java. lang. reflect. proxy; 2 import java. lang. reflect. invocationHandler; 3 import java. lang. reflect. method; 4 import java. lang. reflect. invocationTargetException; 5 6 // interface 7 interface Fruit {8 public abstract void addFruit (); 9} 10 11 // implementation class 12 class FruitImpl implements Fruit {13 @ Override 14 public void addFruit () {15 System. out. println ("add fruit... "); 16} 17} 18 19 // test class --- compile the proxy and enhance Method 20 in the implementation class Public class FruitDemo {21 public static void main (String [] args) {22 // create a dynamic Proxy Object 23 Object f = Proxy. newProxyInstance (FruitImpl. class. getClassLoader (), FruitImpl. class. getInterfaces (), 24 new InvocationHandler () {25 @ Override 26 public Object invoke (Object Proxy, Method method, Object [] args) {27 System. out. println ("select fruit ..................... "); 28 Object obj = null; 29 try {30 obj = method. invoke (New FruitImpl (), args); 31} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {32 e. printStackTrace (); 33} 34 System. out. println ("added successfully ~~ "); 35 return obj; 36} 37} 38); 39 40 // proxy object downward (Interface) transformation 41 Fruit f1 = (Fruit) f; 42 43 // the original method (enhanced) of the object after transformation 44 f1.addFruit (); 45} 46} 47