Dom4j读取xml文件 实现依赖注入

Java反射机制

反射:运行时 动态加载类
加载类:将class文件读入内存,并为之创建一个Class对象。

获得Class

通过class类的静态方法:Class.forName(String className)

	Class stuClass = Class.forName("Student");

通过类初始化对象

初始化对象:newInstance(); 只能调用无参构造。并不是new对象哦。

Object stu = stuClass.newInstance();

为对象的属性赋值

在Java反射中Field类用来操作类的属性

获得Field对象:

Field allStuClassField = stuClass.getDeclaredFields();//获取该类的所有属性
Field stuIdField = stuClass.getDeclaredField(stuId);//获取特定属性

getDeclaredFields()和getFields()的区别:

getFields() 获取所有public字段,包括父类字段
getDeclaredFields() 获取所有字段 public和protected和private,但是不包括父类字段

改变Student实例的属性值:

stuIdField.set(stu,"2018302110402");//stu是一个实例

获取属性的类型:

stuIdField.getType();

读取XML文件并创建对象容器类

XML的解析方式有四种,分别是:DOM解析;SAX解析;JDOM解析;DOM4J解析。前两种属于官方自带的解析方式,与平台无关;后两者是扩展方法,只适用于Java平台。

引入dom4j.jar

Dom4j文档

步骤:加载xml,读取根节点,遍历结点、遍历属性。

一个栗子:任务目标

ObjectContainer类

public class ObjectContainer  {
	//定义元素的名字
    private static final String ID="id";
    private static final String CLASS="class";
    private static final String NAME="name";
    private static final String VALUE="value";
	//用来都xml文件的document
    private Document document;
    //对象容器的实体
    public ArrayList<JiaoTongGongJu> container=new ArrayList<JiaoTongGongJu>();

    public ObjectContainer(String path) throws DocumentException, ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        //获取xml文件
        SAXReader reader = new SAXReader();
        document = reader.read(new File(path));
        //获取根节点
        Element rootNode = document.getRootElement();
        this.getBean(rootNode);
    }

    public ArrayList<JiaoTongGongJu> getBean(Element rootNode) throws IllegalAccessException, ClassNotFoundException, InstantiationException, NoSuchFieldException {
        //获得根结点(beans)子节点的list(bean的list)
        List<Element> beanList=rootNode.elements();
        //遍历根结点的子结点
        for(Element bean: beanList){
            //找id
            String beanId = bean.attributeValue(ID);
            if(beanId==null){continue;}
            //找class
            String beanClass = bean.attributeValue(CLASS);
            if(beanClass == null) {
                throw new RuntimeException("Error:Class not found!");
            }
            //找到类了则加载类并初始化对象
            Object instance = Class.forName(beanClass).newInstance();
            Field name = Class.forName(beanClass).getField("name");
            name.set(instance,beanId);

            //为property赋值,三级节点
            List<Element> propList = bean.elements();
            for(Element prop:propList){
                Field field = instance.getClass().getField(prop.attributeValue(NAME));
                //如果属性的类型是int
                if(field.getType().equals(int.class)){
                    int intValue=Integer.parseInt(prop.attributeValue(VALUE));
                    field.set(instance,intValue);
                    continue;
                }
                field.set(instance, prop.attributeValue(VALUE));
            }
            container.add((JiaoTongGongJu) instance);
        }
        return container;
    }
}

XML

<beans>
    <bean id="plane1" class="Plane">
        <property name="startAddr" value="NewYork"/>
        <property name="distance" value="3000"/>
        <property name="price" value="1000"/>
    </bean>

    <bean id="plane2" class="Plane">
        <property name="startAddr" value="Nanjing"/>
        <property name="distance" value="5000"/>
        <property name="price" value="1000"/>
    </bean>

    <bean id="ship1" class="Ship">
        <property name="startAddr" value="Shanghai"/>
        <property name="distance" value="1000"/>
        <property name="price" value="300"/>
    </bean>

    <bean id="car1" class="Car">
        <property name="startAddr" value="Beijing"/>
        <property name="distance" value="500"/>
        <property name="price" value="50"/>
    </bean>

    <bean id="train1" class="Train">
        <property name="startAddr" value="Wuhan"/>
        <property name="distance" value="3000"/>
        <property name="price" value="250"/>
    </bean>

</beans>

交通工具抽象类

抽象类不能创建实例对象 只能被继承

public abstract class JiaoTongGongJu implements Methods{
    public String name;
    public int price;
    public String startAddr;
    public int distance;

    public JiaoTongGongJu(){
    }
    public String getName(){
        return name;
    }
    @Override
    public void transport() {
        System.out.println("The "+this.getName()+" begin to transport..."
                + "\t(Price:"+getPrice()+", "
                +"StartAddress:"+getStartAddr()+", "
                +"Distance:"+getDistance()+")");
    }
    @Override
    public String getStartAddr(){return startAddr;}
    @Override
    public int getDistance(){return distance;}
    @Override
    public int getPrice(){
        return this.price;
    }
}

方法接口

接口里的方法不能有任何函数体 接口必须是public

public interface Methods {
    public void transport() ;
    public String getStartAddr();
    public int getDistance();
    public int getPrice();
}

各种交通工具实体类

public class Car extends JiaoTongGongJu {
    public Car(){}
}
public class Plane extends JiaoTongGongJu{
    public Plane(){}
}
public class Ship extends JiaoTongGongJu {
    public Ship(){}
}
public class Train extends JiaoTongGongJu {
    public Train(){}
}

测试类

public class Main {
    public static void main(String[] args) throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        ObjectContainer oc=new ObjectContainer("src/jiaotonggongju.xml");
        for(JiaoTongGongJu i:oc.container){
            i.transport();
        }
    }
}

输出

在这里插入图片描述

发布了36 篇原创文章 · 获赞 0 · 访问量 1772

猜你喜欢

转载自blog.csdn.net/Oneiro_qinyue/article/details/103056996