jdk动态代理接口

JDK动态代理能对实现了接口的类进行代理,采用JDK动态代理必须实现InvocationHandler接口,采用Proxy类创建相应的代理类。

 

代码示例:

接口
[java] view plaincopyprint?

    package com.jialin;  
      
    public interface InterfaceUserManage {  
        public void AddUser(String userName,String userAge);  
        public void DelUser();  
        public void ModifyUser();  
    }  


目标类
[java] view plaincopyprint?

    package com.jialin;  
      
    public class UserManageImp implements InterfaceUserManage {  
      
        @Override  
        public void AddUser(String userName,String userAge) {  
            System.out.println("UserManageImp>>>>>AddUser("+userName+","+userAge+")");  
        }  
      
        @Override  
        public void DelUser() {  
            System.out.println("UserManageImp>>>>>DelUser");  
        }  
      
        @Override  
        public void ModifyUser() {  
            System.out.println("UserManageImp>>>>>ModifyUser");  
        }  
      
    }  


代理
[java] view plaincopyprint?

    package com.jialin;  
      
    import java.lang.reflect.InvocationHandler;  
    import java.lang.reflect.Method;  
    import java.lang.reflect.Proxy;  
      
    public class PublicProxy implements InvocationHandler {  
      
        private Object targetObject;  
          
        public Object newProxyInstance(Object targetObject) {  
            this.targetObject = targetObject;  
            return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),  
                                   targetObject.getClass().getInterfaces(), this);  
        }  
          
        public Object invoke(Object proxy, Method method, Object[] args)  
                throws Throwable {  
            System.out.println("开始调用目标方法-->>" + method.getName());  
            for (int i=0; i<args.length; i++) {  
                //打印调用目标方法的参数  
                System.out.println(args[i]);  
            }  
              
            try {  
                //调用目标方法  
                method.invoke(targetObject, args);  
                System.out.println("调用-->>" + method.getName()+"--成功");   
            }catch(Exception e) {  
                e.printStackTrace();  
                System.out.println("调用-->>" + method.getName()+"--失败");  
                throw e;  
            }  
            return null;  
        }  
      
    }  


客户端
[java] view plaincopyprint?

    package com.jialin;  
      
    public class Client {  
        public static void main(String[] args)  
        {  
            PublicProxy publicProxy = new PublicProxy();  
            InterfaceUserManage userManager = (InterfaceUserManage)publicProxy.newProxyInstance(new UserManageImp());  
            userManager.AddUser("王五","17");  
        }  
    }  


输出结果:

开始调用目标方法-->>AddUser
王五
17
UserManageImp>>>>>AddUser(王五,17)
调用-->>AddUser--成功

你可能感兴趣的:(jdk动态代理接口)