问答详情
源自:1-3 实现一个自己的IoC

我的也报空指针异常,能麻烦老师看一下吗?谢谢!

class Person {
    private Car car;
    public Person(Car car){
        this.car=car;
    }
    public void goHome(){
        car.start();
        car.drive();
        car.stop();
    }
}

class Car{
     public Car(){}
     public void start(){}
     public void drive(){}
     public void stop(){}
}

class IoCContainer{
    private Map<String,Object> beans=new ConcurrentHashMap<>();

    public Object getBean(String beanID){
        return beans.get(beanID);
    }

    public void setBean(Class<?> clazz,String beanID,String... paramBeanIDs){
        //1.组装构造方法需要的参数值
        Object[] paramValues=new Object[paramBeanIDs.length];
        for(int i=0;i<paramValues.length;i++){
            paramValues[i]=beans.get(paramBeanIDs);
        }
        //2.调用构造方法实例化bean
        Object bean=null;
        for(Constructor<?> constructor:clazz.getConstructors()){
            try {
                bean=constructor.newInstance(paramValues);
            } catch (InstantiationException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
        if(bean==null){
            throw new RuntimeException("找不到bean");
        }
        //3.将实例化的bean放入beans
       beans.put(beanID,bean);
    }
}


public class Test2{
    private IoCContainer container=new IoCContainer();

    @Before
    public void before(){
        container.setBean(Car.class,"car");
        container.setBean(Person.class,"person","car");
    }

    @Test
    public void test(){
        Person zhangSan=(Person) container.getBean("person");
        zhangSan.goHome();
    }

}


提问者:xintf 2019-07-12 14:26

个回答

  • 信影子慕
    2019-07-12 14:44:59

    https://img4.mukewang.com/5d282c0a0001334604760103.jpg

    这个地方写错了