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(); } }
这个地方写错了