Implementation of the Java proxy

Source: Internet
Author: User

1. Create a new interface Userdao

public interface userdao{

public void Save (User u);

}

2. Implement the interface

public class Userdaoimpl implements userdao{

public void Save (User u) {

System.out.println (u+ "save!");

}

}

3. Create a new business logic object to add a log when calling the method of the Proxied object

public class Logintercepter implements invocationhander{

Private object target;//The target object, also called the Proxied object

Public Object Gettarget () {

return target;

}

public object Settarget (object target) {

This.target =target;

}

public void Beforemethod (Method m) {

System.out.println (M.getname () + "Start,log remeber! ");

}

public object Invoke (Object Proxy,method m,object[] args) {

Beforemethod (m);

M.invoke (Target,args);

return null;

}

}

public void Testproxy () {//test method

Userdao userdao=new Userdaoimpl ();

Logintercepter li=new Logintercepter ();

Li.settarget (Userdao);//Set the object to be proxied

Userdao userdaoproxy = (Userdao) proxy.newproxyinstance (Userdao.getclass (). getClassLoader (), UserDAO.getClass (). Getinterfaces (), Li);

Userdaoproxy is a proxy object for Userdao
Userdaoproxy.save (New User ());

}

Native Java implements several key points of dynamic agent

1. The proxy object must be an interface form

2, the specific business logic object must implement the Invocationhander interface, and rewrite the Invoke method, while the proxy object can be set in

3. When you create a proxy object, Proxy.newproxyinstance (... ) method, note the incoming parameter

Implementation of the Java proxy

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.