NPE在委派期间投掷

时间:2014-06-14 09:12:27

标签: java interface factory-pattern delegation anonymous

我尝试实现dao对象工厂:从类(HUser.class)中获取地图(HDaoFactory.creators)中的某个类(HUserDao)的新实例我们一把钥匙。

我有这段代码:

package com.hxx.model.dao;    
public interface DaoFactory {
        GenericDao getDao(Class dtoClass);
    }


package com.hxx.model.dao;
import java.util.Map;
public class HDaoFactory implements DaoFactory {

    public static Map<Class, DaoCreator> creators;

    public interface DaoCreator { 
        public GenericDao create();
    } 

    @Override
    public GenericDao getDao(Class dtoClass) {
        DaoCreator creator = creators.get(dtoClass); 
        if (creator == null) { 
        } 
        return creator.create(); 
    }

}

在执行静态初始化块期间:

package com.hxx.model.core;

import com.hxx.model.dao.HDaoFactory;
import com.hxx.model.dao.HUserDao;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HUser extends HObjectAbstract {
    public HUser() {
    }

    static {
        try {
            HDaoFactory.creators.put(HUser.class, new HDaoFactory.DaoCreator() {
                @Override
                public GenericDao create() {
                    return new HUserDao();
                }
            });
        } catch(Exception ex) {
            Logger.getLogger(HUser.class.getName()).log(Level.SEVERE, 
                HUser.class.getName().concat(".<init>: creating of dao instance has failed."));
                ex.printStackTrace(System.out);
        }
    }
NPE:

SEVERE: com.hxx.model.core.HUser.<init>: creating of dao instance has failed.
INFO: java.lang.NullPointerException
    at com.hxx.model.core.HUser.<clinit>(HUser.java:48)
    at com.hxx.controller.UserBean.<init>(UserBean.java:43)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:357)
    at java.lang.Class.newInstance(Class.java:310)
    at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)

我做错了什么?

1 个答案:

答案 0 :(得分:0)

creators地图似乎未在任何地方初始化,从而产生NullPointerException。有一个好的线程here,它非常清楚地解释了如何追踪NPE。