在目前的Java开发包中包含了对动态代理的支持,但是其实现只支持对接口的的实现。
其实现主要通过是Java.lang.reflect.Proxy类和java.lang.reflect.InvocationHandler接口。
Proxy类主要用来获取动态代理对象,InvocationHandler接口用来约束调用者实现
业务接口
- package com.itmyhome.manager;
-
- public interface UserManager {
- public void addUser();
- public boolean delUser(int id);
- }
业务接口实现
- package com.itmyhome.manager;
-
-
- public class UserManagerImpl implements UserManager {
-
- @Override
- public void addUser() {
-
- System.out.println("--addUser()--");
- }
-
- @Override
- public boolean delUser(int id) {
-
- System.out.println("--delUser()--");
- return true;
- }
-
- }
InvocationHandler实现 测试在调用接口方法前输出一行代码
- package com.itmyhome.manager;
-
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
-
- public class ProxyHandler implements InvocationHandler {
- private Object obj;
- public Object createProxy(Object obj){
- this.obj = obj;
- return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
- obj.getClass().getInterfaces(),
- this);
- }
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
-
- check();
- Object temp = method.invoke(this.obj, args);
- return temp;
- }
- public void check(){
- System.out.println("---check()---");
- }
-
- }
测试代码
- package com.itmyhome.manager;
-
- public class Client {
-
-
-
-
- public static void main(String[] args) {
-
- ProxyHandler handler = new ProxyHandler();
- UserManager userManager = (UserManager)handler.createProxy(new UserManagerImpl());
- userManager.addUser();
- userManager.delUser(1);
- }
-
- }
转载出处: http://blog.csdn.net/itmyhome1990/article/details/7171370