动手写web框架(3): Bean容器 发表于 2017-02-16 | 分类于 动手写web框架 通过ClassHepler类可以获取相关的已加载的类,但是无法获取到类的实例,因而要完成Bean容器,必须借助反射来实例化相应的Bean对象,最后通过一个Map集合维护所有类和对象之间的映射关系。 BeanHelper12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758package org.smart4j.framework.helper;import org.smart4j.framework.util.ReflectionUtil;import java.util.HashMap;import java.util.Map;import java.util.Set;/** * 相当于Bean容器 * Created by Roger on 2016/11/23. */public final class BeanHelper { /** * 定义Bean映射(存放Bean类与Bean实例的映射) */ private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<>(); static { Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet(); for (Class<?> beanCls: beanClassSet){ Object obj = ReflectionUtil.newInstance(beanCls); BEAN_MAP.put(beanCls, obj); } } /** * 获取bean映射 * @return */ public static Map<Class<?>, Object> getBeanMap(){ return BEAN_MAP; } /** * 获取bean实例 * @param cls * @param <T> * @return */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> cls){ if (!BEAN_MAP.containsKey(cls)){ throw new RuntimeException("can not get bean by class:" + cls); } return (T) BEAN_MAP.get(cls); } /** * 设置Bean实例 * @param cls * @param obj */ public static void setBean(Class<?> cls, Object obj){ BEAN_MAP.put(cls, obj); }} ReflectionUtil12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273package org.smart4j.framework.util;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.lang.reflect.Field;import java.lang.reflect.Method;/** * 反射工具类 * 实例化对象, 方法调用, 设置成员变量 * Created by Roger on 2016/11/23. */public final class ReflectionUtil { private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class); /** * 创建实例 * @param cls * @return */ public static Object newInstance(Class<?> cls){ Object instance; try { instance = cls.newInstance(); } catch (Exception e) { LOGGER.error("new instance failure", e); throw new RuntimeException(e); } return instance; } /** * 调用方法 * @param obj * @param method * @param args * @return */ public static Object invokeMethod(Object obj, Method method, Object... args){ Object result; try { method.setAccessible(true); int paramCount = method.getParameterCount(); if (paramCount > 0){ result = method.invoke(obj, args); }else { result = method.invoke(obj); } } catch (Exception e) { LOGGER.error("invoke method failure", e); throw new RuntimeException(e); } return result; } /** * 设置成员变量的值 * @param obj * @param field * @param value */ public static void setField(Object obj, Field field, Object value){ try { field.setAccessible(true); field.set(obj, value); } catch (IllegalAccessException e) { LOGGER.error("set field failure", e); throw new RuntimeException(e); } }}