package com.it.java;
import java.lang.reflect.Field;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.it.entity.UserEntity;
/**
* 利用反射手写springioc
* @author proxy
*
*/
public class ClassPathXmlApplicationContext {
private String xmlPath;
public ClassPathXmlApplicationContext(String xmlPath) {
super();
this.xmlPath = xmlPath;
}
public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException{
//一.读取xml配置文件
SAXReader saxReader = new SAXReader();
//1.获取当前项目路径
Document read = saxReader.read(this.getClass().getClassLoader().getResourceAsStream(xmlPath));
//2.获取根节点对象
Element rootElement = read.getRootElement();
List
elements = rootElement.elements();
Object obj =null;
for (Element sonEle : elements) {
//二.获取道每个Bean配置,获取class地址
String sonBeanId =sonEle.attributeValue("id");
if(!beanId.equals(sonBeanId)){
continue;
}
String beanClassPath = sonEle.attributeValue("class");
Class> forName = Class.forName(beanClassPath);
obj=forName.newInstance();
//4。拿到成员属性
List sonSoneleme = sonEle.elements();
for (Element element : sonSoneleme) {
String name =element.attributeValue("name");
String value =element.attributeValue("value");
//三.拿到class地址 进行反射实例化对象,使用反射api为私有属性赋值
Field declaredField = forName.getDeclaredField(name);
//运行往私有成员赋值
declaredField.setAccessible(true);
declaredField.set(obj, value);
}
}
//3.拿到class 地址 进行反射实力化对象
return obj;
}
public static void main(String[] args) throws
DocumentException, ClassNotFoundException, InstantiationException,
IllegalAccessException, NoSuchFieldException, SecurityException {
//读取xml
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("user.xml");
//读取beanid
Object bean = classPathXmlApplicationContext.getBean("user1");
//拿到实体类
UserEntity user = (UserEntity) bean;
System.out.println(user.getUserId()+"-----"+user.getUserName());
}
}
-------------------------------------------------------------------------------------------------------------------------------
package com.it.entity;
public class UserEntity {
private String userId;
private String userName;
public UserEntity(){
System.out.println("使用反射技术 ,执行无参数构造 函数");
}
public UserEntity(String userId,String userName) {
System.out.println("使用反射技术 执行 有参构造函数 userId:"+userId+"----userName:"+userName);
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
-------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------