Dynamic Proxy Case 1: use proxy dynamic Proxy to enhance the method. Use Case proxy

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.