我是靠谱客的博主 忧虑啤酒,这篇文章主要介绍用反射机制读出类中的信息,现在分享给大家,希望可以做个参考。

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


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

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


1.Animal类中的具体内容

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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中的内容

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
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.配置文件中的内容

复制代码
1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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()即可得到结果。


最后

以上就是忧虑啤酒最近收集整理的关于用反射机制读出类中的信息的全部内容,更多相关用反射机制读出类中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(71)

评论列表共有 0 条评论

立即
投稿
返回
顶部