- 浏览: 102817 次
- 性别:
- 来自: 杭州
最新评论
-
whatlonelytear:
赞
java注解应用实例 - Annotation, 自定义注解, 注解类规则 -
砚台观月:
你好,例子还有吗,我想要份学习看下。提供的链接找不到了。
java网络编程之Http多线程下载应用实例 -
xianghanscce:
...
java泛型应用实例 - 自定义泛型类,方法 -
yhx1231:
...
Java反射应用实例 -
beiyeren:
写的不错啊
java注解应用实例 - Annotation, 自定义注解, 注解类规则
本文主要通过Java反射应用实例来讲解 利用反射方法创建对象(使用默认构造函数和自定义构造函数) ,访问对应对象的方法(包括带参数的和不带参数的),访问对应对象的域(Field) . 从 这里 可以下载到完整的java代码工程: http://download.csdn.net/detail/hejiangtao/4011663
很多IOC等框架都使用反射来实现,例如Spring, Hibernate等, Java反射的方式实现的逻辑比普通类逻辑的效率是要差一些的(14至300倍左右), 具体可以参考我转载的一篇文章<java反射的性能问题 >http://blog.csdn.net/hejiangtao/article/details/7188835.
首先看下我们实例中被访问的类DataTypeBean.java:
这个Bean中定义了4种类型的Field,包含了int, String,String数组和List; 定义了默认构造函数和自定义的构造函数; 还有一个给List域赋值的带参数函数; 一个不带参数的toString函数.我们要实现的就是使用反射的方法来访问这些Fields 和Methods.
- package com.ross.reflect.bean;
- import java.util.*;
- /**
- * Author: Jiangtao He; Email: ross.jiangtao.he@gmail.com
- * Date: 2012-1-4
- * Since: MyJavaExpert v1.0
- * Description: It will contains some typical fields whose data types
- * are using frequently. it will be used in the reflect test
- */
- public class DataTypeBean
- {
- private int iInt;
- private String sStr;
- private String[] saStr;
- List< Integer > oList;
- // default constructor
- public DataTypeBean()
- {
- }
- // constructor with parameters
- public DataTypeBean(int iInt, String sStr, String[] saStr,
- List< Integer > oList)
- {
- this.iInt = iInt;
- this.saStr = saStr;
- this.sStr = sStr;
- this.oList = oList;
- }
- // method with parameter, it will set value of the list field
- public void addDataToList(int iStart, int iEnd)
- {
- if (iStart < iEnd )
- {
- oList = new ArrayList < Integer > ();
- while (iStart < = iEnd)
- {
- oList.add(iStart);
- iStart++;
- }
- }
- }
- // method without parameter
- public String toString()
- {
- StringBuffer sbStr = new StringBuffer();
- sbStr.append("Values of the fields of DataTypeBean: iInt = ");
- sbStr.append(this.iInt).append(" ; ");
- for (int i = 0 ; i < this.saStr.length ; i++)
- {
- sbStr.append("saStr").append("[").append(i).append("]").append(
- " = ").append(saStr[i]).append(" ; ");
- }
- for (int j = 0 ; j < this.oList.size (); j++)
- {
- sbStr.append("oList.get").append("(").append(j).append(")").append(
- " = ").append(oList.get(j)).append(" ; ");
- }
- return sbStr.toString();
- }
- //省略了set/get方法
- }
来看我们的反射的实现类MyReflect.java, 由于担心代码太长不好看,就全部在Main函数里面写了,方便看.
1. 首先我们看下使用默认构造函数创建类对象, 并通过访问Field对象来给类对象赋值, 最后通过toString方法打印字符串.
初始化我们要使用的参数, 这些参数将用于给类的Field赋值:
获取 DataTypeBean的类,和我们将要用到的方法对象, 其中toString方法是不带参数的,addDataToList则是带参数的. 由此可以看出我们在使用反射方法的时候是需要知道参数个数和参数类型的:[html] view plain copy
- int iInt = 2012 ;
- String sStr = "This a string!" ;
- String[] saStr = new String[] { "First item of the string array",
- "Second item of the string array",
- "Third item of the string array" };
- List< Integer > oList = new ArrayList < Integer > ();
- // Initialize the oList
- int i = 0 ;
- while (i < 3 )
- {
- oList.add(i);
- i++;
- }
使用默认构造函数创建一个 DataTypeBean的对象:[html] view plain copy
- // get class
- Class oClass = Class.forName("com.ross.reflect.bean.DataTypeBean");
- // get the toString method, a method without parameters
- Method oToStringMethod = oClass .getMethod("toString");
- // get the addDataToList method, a method with parameters
- Method oAddDataToListMethod = oClass .getMethod("addDataToList",
- int.class, int.class);
使用反射方法访问Field来给对象赋值:[html] view plain copy
- // used default constructor to initialize a object
- Object oDefalutObject = oClass .newInstance();
通过反射方法调用 DataTypeBean的toString方法将赋值后的 DataTypeBean打印出来:[html] view plain copy
- // access fields process, getDeclaredFields can access private and
- // protected fields
- Field[] oFields = oClass .getDeclaredFields();
- for (int j = 0 ; j < oFields.length ; j++)
- {
- // to access the private
- oFields[j].setAccessible(true);
- // getSimpleName method can get the type of the field, according the
- // field type set the data to the field
- if ("int".equals(oFields[j].getType().getSimpleName()))
- {
- oFields[j].setInt(oDefalutObject, iInt);
- }
- else if ("String[]".equals(oFields[j].getType().getSimpleName()))
- {
- oFields[j].set(oDefalutObject, saStr);
- }
- else if ("String".equals(oFields[j].getType().getSimpleName()))
- {
- oFields[j].set(oDefalutObject, sStr);
- }
- else if ("List".equals(oFields[j].getType().getSimpleName()))
- {
- oFields[j].set(oDefalutObject, oList);
- }
- }
运行后,我们的控制台打印出如下信息:[html] view plain copy
- // print the object
- String sBeanString = (String) oToStringMethod.invoke(oDefalutObject);
- System.out
- .println("the string of the object created by defaut constructor: "
- + sBeanString);
[html] view plain copy
- the string of the object created by defaut constructor: Values of the fields of DataTypeBean: iInt = 2012 ;
- saStr[0] = First item of the string array ; saStr[1] = Second item of the string array ; saStr[2] = Third item
- of the string array ; oList.get(0) = 0 ; oList.get(1) = 1 ; oList.get(2) = 2 ;
2.
我们再看下使用自定义构造函数创建类对象, 并通过带参数的函数给其List域赋值, 最后通过toString方法打印字符串.
变更下我们要用的参数, 好在控制台上跟默认构造函数创建的对象的打印信息做区分:
使用自定义构造函数创建类对象:[html] view plain copy
- // initialize the parameters for customized constructor, the oList will
- // be initialized by the method with parameters
- iInt = 2013 ;
- sStr = "This another string!" ;
- saStr = new String[] { "1st item of the string array",
- "2nd item of the string array", "3rd item of the string array" };
- oList = new ArrayList < Integer > ();
使用带参数的函数给List 域赋值:[html] view plain copy
- // used customized constructor to initialize a object: DataTypeBean(int
- // iInt, String sStr, String[] saStr, List< Integer > oList)
- Constructor oCon = oClass .getConstructor(int.class, String.class,
- String[].class, List.class);
- Object oCustomizedObject = oCon .newInstance(iInt, sStr, saStr, oList);
同样的,通过反射方法调用 DataTypeBean的toString方法将赋值后的 DataTypeBean打印出来:[html] view plain copy
- //Use the method with parameters initialize the List Object
- oAddDataToListMethod.invoke(oCustomizedObject,2013,2015);
运行后,我们的控制台打印如下信息:[html] view plain copy
- // print the object
- sBeanString = (String) oToStringMethod.invoke(oCustomizedObject);
- System.out
- .println("the string of the object created by customized constructor: "
- + sBeanString);
[html] view plain copy
- the string of the object created by customized constructor: Values of the fields of DataTypeBean: iInt = 2013 ;
- saStr[0] = 1st item of the string array ; saStr[1] = 2nd item of the string array ; saStr[2] = 3rd item of the
- string array ; oList.get(0) = 2013 ; oList.get(1) = 2014 ; oList.get(2) = 2015 ; oList.get(3) = 2016 ;
为了方便参考,我将完整的MyReflect.java贴出来了:
- package com.ross.reflect;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * Author: Jiangtao He; Email: ross.jiangtao.he@gmail.com
- * Date: 2012-1-9
- * Since: MyJavaExpert v1.0
- * Description: reflect method implementation and test
- */
- public class MyReflect
- {
- /**
- * Author: Jiangtao He; Email: ross.jiangtao.he@gmail.com
- * Date: 2012-1-9
- * Description: Use reflect method to access the fields and methods of DataTypebean
- */
- public static void main(String[] args) throws ClassNotFoundException,
- SecurityException, NoSuchMethodException, InstantiationException,
- IllegalAccessException, IllegalArgumentException,
- InvocationTargetException
- {
- int iInt = 2012 ;
- String sStr = "This a string!" ;
- String[] saStr = new String[] { "First item of the string array",
- "Second item of the string array",
- "Third item of the string array" };
- List< Integer > oList = new ArrayList < Integer > ();
- // Initialize the oList
- int i = 0 ;
- while (i < 3 )
- {
- oList.add(i);
- i++;
- }
- // get class
- Class oClass = Class.forName("com.ross.reflect.bean.DataTypeBean");
- // get the toString method, a method without parameters
- Method oToStringMethod = oClass .getMethod("toString");
- // get the addDataToList method, a method with parameters
- Method oAddDataToListMethod = oClass .getMethod("addDataToList",
- int.class, int.class);
- // used default constructor to initialize a object
- Object oDefalutObject = oClass .newInstance();
- // access fields process, getDeclaredFields can access private and
- // protected fields
- Field[] oFields = oClass .getDeclaredFields();
- for (int j = 0 ; j < oFields.length ; j++)
- {
- // to access the private
- oFields[j].setAccessible(true);
- // getSimpleName method can get the type of the field, according the
- // field type set the data to the field
- if ("int".equals(oFields[j].getType().getSimpleName()))
- {
- oFields[j].setInt(oDefalutObject, iInt);
- }
- else if ("String[]".equals(oFields[j].getType().getSimpleName()))
- {
- oFields[j].set(oDefalutObject, saStr);
- }
- else if ("String".equals(oFields[j].getType().getSimpleName()))
- {
- oFields[j].set(oDefalutObject, sStr);
- }
- else if ("List".equals(oFields[j].getType().getSimpleName()))
- {
- oFields[j].set(oDefalutObject, oList);
- }
- }
- // print the object
- String sBeanString = (String) oToStringMethod.invoke(oDefalutObject);
- System.out
- .println("the string of the object created by defaut constructor: "
- + sBeanString);
- // initialize the parameters for customized constructor, the oList will
- // be initialized by the method with parameters
- iInt = 2013 ;
- sStr = "This another string!" ;
- saStr = new String[] { "1st item of the string array",
- "2nd item of the string array", "3rd item of the string array" };
- oList = new ArrayList < Integer > ();
- // used customized constructor to initialize a object: DataTypeBean(int
- // iInt, String sStr, String[] saStr, List< Integer > oList)
- Constructor oCon = oClass .getConstructor(int.class, String.class,
- String[].class, List.class);
- Object oCustomizedObject = oCon .newInstance(iInt, sStr, saStr, oList);
- //Use the method with parameters initialize the List Object
- oAddDataToListMethod.invoke(oCustomizedObject,2013,2015);
- // print the object
- sBeanString = (String) oToStringMethod.invoke(oCustomizedObject);
- System.out
- .println("the string of the object created by customized constructor: "
- + sBeanString);
- }
- }
发表评论
-
<转>NetBeans 6.1 界面语言设置
2012-10-07 01:49 2293NetBeans 6.1 界面语言设置从官网下载的NetBea ... -
常见开源协议(BSD,Apache,GPL,LGPL,MIT)
2012-10-05 01:52 956BSD开源协议(original BSD license、Fr ... -
Java相对路径总结<转>
2012-03-04 17:16 10091.基本概念的理解 绝对路径:绝对路径就是你的主页上的文件或 ... -
Java Compiler 应用实例
2012-02-09 01:22 6968一直在用JDK1.5, 一直搞不清楚JDK1.6有啥特性, 就 ... -
java注解应用实例 - Annotation, 自定义注解, 注解类规则
2012-01-29 21:35 25582本文介绍了java的自定义注解及注解类编写的规则, 并通过实例 ... -
Java 序列化的高级认识--序列化反序列化, 加密存储<转>
2012-01-29 15:21 2265简介: 文章对序列化进行了更深一步的讨论,用实际的例子 ... -
java网络编程之Http多线程下载应用实例
2012-01-21 02:34 8603本demo 通过RandomAccessFile, URLC ... -
java反射的性能问题 (转)
2012-01-14 23:36 2234很多IOC,还有框架都使用反射。特别是在通过反射调用方法的时候 ... -
java泛型应用实例 - 自定义泛型类,方法
2012-01-14 23:19 37358注: 转载请注明出处: http://hejiangtao.i ... -
泛型的效率和原始类的效率比较(转)
2012-01-14 23:16 1812用 了好久的泛型,突然听到有人说:泛型影响效率! 嘿, ... -
文本数据库的简单java实现
2012-01-14 22:58 7201注: 转载请注明出处: ...
相关推荐
Java反射机制经典案例
java反射机制应用,文档中列举了使用java反射机制的各个应用场景,加以代码实例,使用学习非常方便。
NULL 博文链接:https://dragonmandance.iteye.com/blog/2336911
代码为JAVA反射的一个DEMO,适合初学者临摹学习,还附有properties的创建方法,比较基础。
Java中,反射是一种强大的工具。它使您能够创建灵活的代码,这些代码可以在运行时装配,无需在组件 之间进行源代表链接。反射允许我们在编写与执行时,使我们的程序代码能够接入装载到JVM中的类的内 部信息,而不是...
在不知道类名的情况下如何动态的使用其构造方法来创建对象和不知道其方法名的时候如何动态地使用其方法。
本文档对Java中使用最广的反射进行了深度而让人简单容易理解的解析,附有实例,可供致力于java底层研究的人提供借鉴
反射实例-JAVA反射机制,基本知识介绍和简单的应用
java的反射机制的应用实例,对反射的机制很好的理解!
本实例教程分反射对成员变量、构造器、方法操作,详尽而简略得列出反射机制的应用,希望对大家有用。
java反射学习的一些基础代码,简单使用反射的案例,为eclipse中的工作空间,编码GBK
Java提供了一套机制来动态执行方法和构造方法,以及数组操作等,这套机制就叫——反射。反射机制是如今很多流行框架的实现基础,其中包括Spring、Hibernate等。原理性的问题不是本文的重点,接下来让我们在实例中...
3.2 相关知识 3.2.1 Java反射机制的概念 3.2.2 反射机制的功能 3.2.3 Java反射机制的相关API 3.2.4 使用反射机制的步骤 3.2.5 反射机制的应用场景 3.2.6 反射机制的优缺点 Java高级程序设计实战教程第三章-Java反射...
Java IOC(控制反转)及反射api应用代码参考实例
以下是Java反射技术的一些常见应用: 获取类的信息:通过反射可以获取类的名称、父类、接口、方法、字段等信息。 实例化对象:通过反射可以实例化一个类的对象,即使在编译时并不知道具体的类名。 调用方法:通过...
主要介绍了Java反射技术原理与用法,结合实例形式分析了Java反射技术的基本概念、功能、原理、用法及操作注意事项,需要的朋友可以参考下
JAVA反射机制与类的加载,详细的说明java反射机制的实例以及应用是入门级的课件
·课程共30天,715个知识视频小节,涉及主流Java使用的方方面面,全而不冗余 ·全程内容涵盖数据结构、设计模式、JVM内存结构等深度技术 ·企业级笔试面试题目深入源码级讲解,拒绝死记硬背 4.代码量更大、案例更...