Cglib 实现动态代理Proxy

package com.baidu.cglib;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * 通过Cglib实现在方法调用前后向控制台输出两句字符串
 * 
 * @author jiqinlin
 *
 */
public class CglibProxy implements MethodInterceptor {

    public Object createProxy(Class<?> targetClass) {
       // this.obj = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetClass);// 设置代理目标
        enhancer.setCallback(this);// 设置回调
        enhancer.setClassLoader(targetClass.getClassLoader());
       
        return enhancer.create();
    }


    /**
     * 在代理实例上处理方法调用并返回结果
     * 
     * @param proxy
     *            代理类
     * @param method
     *            被代理的方法
     * @param params
     *            该方法的参数数组
     * @param methodProxy
     */
    public Object intercept(Object proxy, Method method, Object[] params,
            MethodProxy methodProxy) throws Throwable {
        Object result = null;
        // 调用之前
        doBefore();
        // 调用原始对象的方法
        result = methodProxy.invokeSuper(proxy, params);
        // 调用之后
        doAfter();
        return result;
    }

    private void doBefore() {
        System.out.println("before method invoke");
    }

    private void doAfter() {
        System.out.println("after method invoke");
    }
    
    
    public static void main(String[] args) {
        
        CglibProxy cglibProxy=new CglibProxy();
        
        HelloWorld hw=(HelloWorld)cglibProxy.createProxy(HelloWorld.class);
        
        hw.sayHelloWorld();
    }

}
package com.baidu.cglib;

public class HelloWorld {
	
    public void sayHelloWorld() {
        System.out.println("HelloWorld!");
    }
}


不同对象的拷贝

package com.baidu2;


import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

import org.apache.commons.beanutils.PropertyUtils;


/**
 * 对象与对象深度拷贝,包括嵌套的复合类型,可以忽略类型,只要有相通的属性名
 * 数组也可以处理,即便dest是一个空数组
 */
public class MyBeanUtils {
	
	
	// 不同对象简单域拷贝
	public static void copy2(Object object1, Object object2) throws Exception {
		Field[] fields = object1.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			String name = fields[i].getName();
			Field field2 = object2.getClass().getDeclaredField(name);

			field2.setAccessible(true);

			Field field1 = fields[i];
			field1.setAccessible(true);

			// System.out.println(field1.getModifiers());
			/*if ((field1.getModifiers() & java.lang.reflect.Modifier.STATIC) != java.lang.reflect.Modifier.STATIC) {
				field2.set(object2, field1.get(object1));
			}*/
			if(!Modifier.isStatic(field1.getModifiers()))
			{
				field2.set(object2, field1.get(object1));
			}

		}

	}

	
	/**
	 * 
	 * @param dest 目标对象
	 * @param orig 原始对象
	 * @throws Exception
	 */
	public static void copy(Object dest, Object orig) throws Exception {
		if (dest == null) {
			throw new IllegalArgumentException("No destination bean specified");
		}
		if (orig == null) {
			throw new IllegalArgumentException("No origin bean specified");
		}
		
		Class origClass = orig.getClass();
		Class destClass = dest.getClass();
		if (origClass == String.class || origClass.isPrimitive()) {
			dest = orig;
		}
		if(orig.getClass().isArray()){
			Object[] destArr = (Object[]) dest;
			Object[] origArr = (Object[]) orig;
			Class elemenClass = destArr.getClass().getComponentType();
			
			for(int i=0;i<origArr.length;i++){
				if(destArr[i]==null){
					destArr[i] = elemenClass.newInstance();
				}
				
				copy(destArr[i], origArr[i]);
			}
		}
		String classLogInfo = "origClass:"+origClass.getName()+",destClass:"+destClass.getName()+",";
		PropertyDescriptor[] origDescriptors = PropertyUtils
				.getPropertyDescriptors(orig);
		for (int i = 0; i < origDescriptors.length; i++) {
			String name = origDescriptors[i].getName();
			if ("class".equals(name)) {
				continue;
			}
			Object value = null;
			if (PropertyUtils.isReadable(orig, name)
					&& PropertyUtils.isWriteable(dest, name)) {
				try {
					value = PropertyUtils.getSimpleProperty(orig, name);
					PropertyUtils.setSimpleProperty(dest, name, value);
				} catch (IllegalArgumentException e) {
					// 类型不同
					try {
						PropertyDescriptor targetDescriptor = PropertyUtils
								.getPropertyDescriptor(dest, name);
						Object new_value = targetDescriptor.getPropertyType()
								.newInstance();
						copy(new_value, value);
//						LOG.info(new_value);
						PropertyUtils.setSimpleProperty(dest, name, new_value);
					}catch(IllegalArgumentException e1){
						//
					} 
					catch (IllegalAccessException e1) {
						throw e1;
					} catch (InvocationTargetException e1) {
						throw e1;
					} catch (NoSuchMethodException e1) {
						throw e1;
					} catch (InstantiationException e1) {
						throw e1;
					}
				} catch (NoSuchMethodException e) {
					throw e;
				} catch (IllegalAccessException e) {
					throw e;
				} catch (InvocationTargetException e) {
					throw e;
				}
			}
		}
	}

	
}



 

你可能感兴趣的:(Cglib 实现动态代理Proxy)