zoukankan      html  css  js  c++  java
  • aop实现

    ****

    1,使用动态代理实现aop

    public interface UserDao {
        void save();
    }
    public class UserDaoImpl implements UserDao {
    
        private String name;
        
        public void save() {
            System.out.println("save() is called, name: "+name);
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        
    }

    ProxyFactory.java

    package com.maple.util;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    import com.maple.dao.UserDao;
    import com.maple.dao.impl.UserDaoImpl;
    
    public class ProxyFactory implements InvocationHandler {
    
        private Object target;
        
        public Object createUserDao(Object target){
            this.target=target;
            return Proxy.newProxyInstance(this.target.getClass().getClassLoader(),
                            this.target.getClass().getInterfaces(), this);
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            System.out.println(proxy.getClass().getName());
            Object result=null;
            UserDaoImpl userDao=(UserDaoImpl)this.target;
            if(userDao.getName()!=null){
                result=method.invoke(userDao, args);
            }else{
                System.out.println("the name is null");
            }
            return result;
        }
    
    }

    测试

    @Test
        public void test() {
            ProxyFactory pf=new ProxyFactory();
            UserDaoImpl u=new UserDaoImpl();
            u.setName("maple");
            UserDao userDao=(UserDao) pf.createUserDao(u);
            userDao.save();
        }

    输出:

    $Proxy5
    save() is called, name: maple

    ****

    有问题在公众号【清汤袭人】找我,时常冒出各种傻问题,然一通百通,其乐无穷,一起探讨


  • 相关阅读:
    606. Construct String from Binary Tree
    696. Count Binary Substrings
    POJ 3255 Roadblocks (次短路)
    POJ 2823 Sliding Window (单调队列)
    POJ 1704 Georgia and Bob (博弈)
    UVa 1663 Purifying Machine (二分匹配)
    UVa 10801 Lift Hopping (Dijkstra)
    POJ 3281 Dining (网络流之最大流)
    UVa 11100 The Trip, 2007 (题意+贪心)
    UVaLive 4254 Processor (二分+优先队列)
  • 原文地址:https://www.cnblogs.com/qingmaple/p/4119689.html
Copyright © 2011-2022 走看看