反射,reflection,听其名就像照镜子一样,可以看见自己也可以看见别人的每一部分。在java语言中这是一个很重要的特性。下面是来自sun公司官网关于反射的介绍:
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
The ability to examine and manipulate a Java class from within itself may not sound like very much, but in other programming languages this feature simply doesn't exist. For example, there is no way in a Pascal, C, or C++ program to obtain information about the functions defined within that program.
One tangible use of reflection is in JavaBeans, where software components can be manipulated visually via a builder tool. The tool uses reflection to obtain the properties of Java components (classes) as they are dynamically loaded.
那么解释一下就是,反射是java语言的一个特性,它允程序在运行时(注意不是编译的时候)来进行自我检查并且对内部的成员进行操作。例如它允许一个java的类获取他所有的成员变量和方法并且显示出来。这个能特定我们不常看到,但是在其他的比如C或者C++语言中很不就存在这个特性。一个常见的例子是在JavaBean中,一些组件可以通过一个构造器来操作。这个构造器就是用的反射在动态加载的时候来获取的java中类的属性的。
反射的前传:类类型 Class Class
java中有一个类很特殊,就是Class类,很多朋友在写程序的时候有用过比如Apple.class来查看类型信息,大家就可以把它理解为封装了类的信息,很多解释说Class类没有构造器,其实是有的,只不过它的构造方法是private的(构造函数还有private的??有,这样是为了禁止开发者去自己创建Class类的实例)。
如果我们拿到一个类的类型信息,就可以利用反射获取其各种成员以及方法了。(注:Class 从JDK1.5版本后就开始更多为泛型服务了)那么我们怎么拿到一个类型的信息呢?假设我们有一个Role类:
- package yui;
- /**
- * A base class having some attributes and methods
- * @author Octobershiner
- * @since 2012 3 17
- *
- * */
- public class Role {
- private String name;
- private String type;
- // Constructors
- public Role(){
- System.out.println("Constructor Role() is invoking");
- }
- //私有构造器
- private Role(String name){
- this.name = name;
- System.out.println("Constructor Role(String name) is invoking.");
- }
- //get and set method
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getType() {
- return type;
- }
- public void setType(String type) {
- this.type = type;
- }
- //override the toString method to show the class
- @Override
- public String toString(){
- return "This is a role called "+this.name;
- }
- }
在没有对象实例的时候,主要有两种办法。
- <span style="font-size:18px;"><strong> //获得类类型的两种方式
- Class cls1 = Role.class;
- Class cls2 = Class.forName("yui.Role");</strong></span>
- <span style="font-size:18px;"><strong> Object o = cls1.newInstance(); //创建一个实例
- //Object o1 = new Role(); //与上面的方法等价</strong></span>
这样就创建了一个对象,缺点是我们只能利用默认构造函数,因为Class的newInstance是不接受参数的,后面会讲到可接受参数的newInstance,第二,如果类的构造函数是private的,比如Class,我们仍旧不能实例化其对象。
获取类的构造器
首先介绍一下Constructor类,这个类用来封装反射得到的构造器,Class有四个方法来获得Constructor对象
- public Constructor<?>[] getConstructors() 返回类中所有的public构造器集合,默认构造器的下标为0
- public Constructor<T> getConstructor(Class<?>... parameterTypes) 返回指定public构造器,参数为构造器参数类型集合
- public Constructor<?>[] getDeclaredConstructors() 返回类中所有的构造器,包括私有
- public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 返回任意指定的构造器
- <span style="font-size:18px;"><strong>/**
- * 获取构造方法Constructor
- * getConstructor() only for public
- * getDeclaredConstructor() global access all
- *
- * */
- //指定参数列表获取特定的方法
- Constructor con = cls1.getDeclaredConstructor(new Class[]{String.class});
- con.setAccessible(true); //设置可访问的权限
- Object obj = con.newInstance(new Object[]{"liyang"});
- System.out.println(obj); //打印一下这个对象的信息
- //获取所有的构造方法集合
- Constructor con1[] = cls1.getDeclaredConstructors();
- con1[1].setAccessible(true);
- Object obj1 = con1[1].newInstance(new Object[]{"tom"});
- System.out.println(obj1);</strong></span>
- public Field getDeclaredField(String name) 获取任意指定名字的成员
- public Field[] getDeclaredFields() 获取所有的成员变量
- public Field getField(String name) 获取任意public成员变量
- public Field[] getFields() 获取所有的public成员变量
- <span style="font-size:18px;"><strong>/**
- * 获取成员变量Field
- * getField()
- * getDeclaredField()
- * */
- Field mem = cls1.getDeclaredField("name");
- mem.setAccessible(true);
- System.out.println("we get form field :"+mem.get(obj));</strong></span>
- public Method[] getMethods() 获取所有的共有方法的集合
- public Method getMethod(String name,Class<?>... parameterTypes) 获取指定公有方法 参数1:方法名 参数2:参数类型集合
- public Method[] getDeclaredMethods() 获取所有的方法
- public Method getDeclaredMethod(String name,Class<?>... parameterTypes) 获取任意指定方法
- <span style="font-size:18px;"><strong>/**
- * 调用类的方法 Method
- * getMethod()
- * getDeclaredMethod()
- *
- * */
- Method f = cls1.getMethod("getName", null);
- Object name = f.invoke(obj, null);
- System.out.println("we invoke method : "+ name);</strong></span>
这个很简单吧,无参的时候我们只要传null就行了。