Java Dynamic proxy dynamic proxy

Source: Internet
Author: User

1. interface of the proxy object:

 
Package test. dynamicproxy; public interface targetinterface {public void sayhello (); Public int sum (int A, int B );}

 

2. Proxy objects:

 
Package test. dynamicproxy; public class target implements targetinterface {public void sayhello () {system. out. println ("hello");} public int sum (int A, int B) {return a + B ;}}

 

3. invocationhandler packaging:

Package test. dynamicproxy; import Java. lang. reflect. invocationhandler; import Java. lang. reflect. method; public class targetinvocationhandler implements invocationhandler {private object; Public targetinvocationhandler (Object OBJ) {This. object = OBJ;} public object invoke (Object proxy, method, object [] args2) throws throwable {dobefore (); object result = method. invoke (object, args2); doafter (); return result;} public void dobefore () {system. out. println ("do before");} public void doafter () {system. out. println ("do after ");}}

4. Test class:

 package test. dynamicproxy; import Java. lang. reflect. proxy; public class testdynamicproxy {/*** @ Param ARGs */public static void main (string [] ARGs) {target T = new target (); targetinvocationhandler handler = new targetinvocationhandler (t); targetinterface proxy = (targetinterface) proxy. newproxyinstance (T. getclass (). getclassloader (), T. getclass (). getinterfaces (), Handler); proxy. sayhello (); int B = proxy. sum (10, 20); system. out. println (B) ;}}

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.