Java中的反射机制2013-12-07 csdn BruceZhang反射,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 Classjava中有一个类很特殊,就是 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 methodpublic 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; }}在没有对象实例的时候,主要有两种办法。
//获得类类型的两种方式Class cls1 = Role.class;Class cls2 = Class.forName("yui.Role");
注意第二种方式中,forName中的参数一定是完整的类名(包名+类名),并且这个方法需要捕获异常。现 在得到cls1就可以创建一个Role类的实例了,利用Class的newInstance方法相当于调用类的默认的构造器
Object o = cls1.newInstance(); //创建一个实例 //Object o1 = new Role(); //与上面的方法等价
这样就创建了一个对象,缺点是我们只能利用默认构造函数,因为Class的newInstance是不接受参数的 ,后面会讲到可接受参数的newInstance,第二,如果类的构造函数是private的,比如Class,我们仍旧不能 实例化其对象。