hibernate学习笔记第13讲-jdk动态代理和CGLib

 

Jdk动态代理,CGLib字节码生成

如果目标对象实现了接口,可以使用jdk动态代理和CGLib

如果没有实现接口,只能使用CGLib

Jdk动态代理要实现一个接口:InvocationHandler

 

public class SecurityHandler implements InvocationHandler {

//目标对象,对该目标对象生成代理

         private Object targetObject;

        

//生成代理对象,当生成完代理对象,调用代理对象上的方法时,默认先调用invoke方法。

         public Object newProxy(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 {

                   checkSecurity();

                   //目标对象方法的返回值

                   Object ret = null;

                   try {

                            //调用目标对象的真实实现

                            ret = method.invoke(this.targetObject, args);

                   }catch(Exception e) {

                            e.printStackTrace();

                            throw new java.lang.RuntimeException(e);

                   }

                   return ret;

         }

         private void checkSecurity() {

                   System.out.println("----------checkSecurity()---------------");

         }}

//使用动态代理

public static void main(String[] args) {

                   SecurityHandler handler = new SecurityHandler();

                   UserManager userManager = (UserManager)handler.newProxy(new UserManagerImpl());

                   //userManager.addUser("张三", "123");

                   userManager.deleteUser(1);

         }

你可能感兴趣的:(java,Hibernate,jdbc,领域模型)