package com.huaao.factory; import java.lang.reflect.Field; import java.lang.reflect.Method; import com.huaao.annotation.AutoInject; import com.huaao.service.TestService; public final class BeanFactory { private static BeanFactory factory = new BeanFactory(); private BeanFactory(){ } public static BeanFactory getBeanFactory(){ return factory; } public Object getBean(Class clazz)throws Exception{ Field[] fields = clazz.getDeclaredFields(); Object instance = clazz.newInstance(); for(Field filed : fields){ if(filed.isAnnotationPresent(AutoInject.class)){ AutoInject inject = filed.getAnnotation(AutoInject.class); String className = inject.name(); String filedName = filed.getName(); Object target = Class.forName(className).newInstance(); Method setMethod = clazz.getMethod("set"+filedName.substring(0,1).toUpperCase()+filedName.substring(1),filed.getType()); setMethod.invoke(instance, target); } } return instance; } public static void main(String[] args)throws Exception { ((TestService)BeanFactory.getBeanFactory().getBean(TestService.class)).test(); } }

telsawu LV1
2023年1月18日
我要赚钱 LV6
2020年11月4日
john93 LV15
2018年12月28日
dagf113225 LV68
2018年12月27日
刚睡醒的麋鹿 LV10
2018年4月2日
li74659526 LV2
2017年10月12日
maojianyun LV30
2017年8月19日
荭琪枫 LV15
2013年5月6日
aitixiaozi LV22
2013年3月23日
yihui1229 LV13
2013年3月21日