Null Objects + cglib2(作者:寸心知)



我把实现concrete class的Null Objects也加上了,是用cglib2来实现的(因此如果你在项目中使用,需要去下载cglib.jar)。看一下源码,注意加粗的部分(注:Pojo中可以不声明constructor,如果有constructors,则必须声明缺省不带任何参数的constructor):

NUll.java

---------------------

import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

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

public class NUll implements InvocationHandler, MethodInterceptor {

    private Map resultValuesByType = new HashMap();

    public NUll() {
        createDefaultResults();
    }

    public static Object object(Class clazz) {
        if (clazz.isInterface()) //interface
         return Proxy.newProxyInstance(clazz.getClassLoader(),
                 new Class[] { clazz }, new NUll());
        else //concrete class
            return Enhancer.create(clazz, new NUll());
    }

    //implement InvocationHandler
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        Class returnType = method.getReturnType();

        if (resultValuesByType.containsKey(returnType)) {
            return resultValuesByType.get(returnType);
        } else if (returnType.isArray()) {
            return Array.newInstance(returnType.getComponentType(), 0);
        } else if (returnType.isInterface()) {
            return NUll.object(returnType);
        } else { 
            return NUll.object(returnType);
        }
    }

    //implement MethodInterceptor
    public Object intercept(Object thisProxy, Method method, Object[] args,
            MethodProxy superProxy) throws Throwable {
        return invoke(thisProxy, method, args);
    }

    public void addResult(Class resultType, Object resultValue) {
        resultValuesByType.put(resultType, resultValue);
    }

    protected void createDefaultResults() {
        addResult(boolean.class, Boolean.FALSE);
        addResult(void.class, null);
        addResult(byte.class, new Byte((byte) 0));
        addResult(short.class, new Short((short) 0));
        addResult(int.class, new Integer(0));
        addResult(long.class, new Long(0L));
        addResult(char.class, new Character('\0'));
        addResult(float.class, new Float(0.0F));
        addResult(double.class, new Double(0.0));
        addResult(Boolean.class, Boolean.FALSE);
        addResult(Byte.class, new Byte((byte) 0));
        addResult(Short.class, new Short((short) 0));
        addResult(Integer.class, new Integer(0));
        addResult(Long.class, new Long(0L));
        addResult(Character.class, new Character('\0'));
        addResult(Float.class, new Float(0.0F));
        addResult(Double.class, new Double(0.0));
        addResult(String.class, "");
    }
}



寸心知
文章千古事,得失寸心知 (作者)

posted on 2004-12-14 22:28  笨笨  阅读(781)  评论(0编辑  收藏  举报

导航