用反射机制读出类中的信息

来源:互联网 发布:muse for mac 编辑:程序博客网 时间:2024/06/06 01:38

题目要求详述:定义一个实体类,利用反射机制找出这个类中的所有的方法、域和构造方法,并显示出类名


Ioc是采用了反射机制的,所以使用Ioc来进行实现。

在具体的实现过程中,所用到的文件如图所示:


1.Animal类中的具体内容

package ioc;public class Animal{    private String animalType;  //何种动物    Animal(String animalType,String movemode)    {    this.animalType = animalType;    this.moveMode = moveMode;    }    public void setAnimalType(String animalType) {        this.animalType = animalType;    }    public String getAnimalType(String animalType) {        return animalType;    }    private String moveMode;  //如何move    public void setMoveMode(String moveMode) {        this.moveMode = moveMode;    }    public String getmoveMode(String moveMode) {        return moveMode;    }    public void getresult() {  //move接口的实现    System.out.println("类名:Animal");    System.out.println("构造函数:setAnimalType");    System.out.println("成员变量:animalType:"+animalType+"moveMode:"+"movemode");    System.out.println("成员函数:setAnimalType、getAnimalType、setMoveMode、getmoveMode");        }}

2.test.java中的内容

package ioc;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;class Test{    public static void main(String []args){        //创建Spring容器        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");        //从容器中获取Animal类的实例       Animal animal = (Animal) ctx.getBean("animal");         //调用move方法        animal.getresult();    }}

3.配置文件中的内容

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="animal" class="ioc.Animal"><constructor-arg index="0" type="java.lang.String" value="Bird" /><constructor-arg index="1" type="java.lang.String" value="fly"/></bean></beans>
在具体实现时,利用主函数进行读取bean.xml中的内容,此时得到在bean.xml中所定义的animaltype和movemode的值,使用构造函数方法注入方式,在主函数中进行实例化animal,调用animal.getresult()即可得到结果。