Java的反射机制是指在程序的运行状态中,可以构造一个Class对象,通过这个对象调用它的方法可以了解任意一个对象所属的类,可以了解任意一个类的成员变量和方法,可以调用任意一个对象的属性和方法。这种动态获取程序信息以及动态调用对象的功能称为Java语言的反射机制。
Class类中常见的方法有:
getName():获得类的完整名字。
getFields():获得类的public类型的属性。
getDeclaredFields():获得类的所有属性。包括private 声明的和继承类
getMethods():获得类的public类型的方法。
getDeclaredMethods():获得类的所有方法。包括private 声明的和继承类
getMethod(String name, Class[] parameterTypes):获得类的特定方法,name参数指定方法的名字,parameterTypes 参数指定方法的参数类型。
getConstructors():获得类的public类型的构造方法。
getConstructor(Class[] parameterTypes):获得类的特定构造方法,parameterTypes 参数指定构造方法的参数类型。
newInstance():通过类的不带参数的构造方法创建这个类的一个对象。
例子:
package Text.textbook.Example6_8;
public class Rect {
double width,height,area;
public Rect(){
}
public Rect(double w,double h){
width = w;
height = h;
}
public double getArea() {
area=height*width;
return area;
}
}
package Text.textbook.Example6_8;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Example6_8 {
public static void main(String args[]) {
Rect rect = new Rect();
Class cs = rect.getClass(); //或 Class cs = Rect.class;
System.out.println(cs == Rect.class); //输出结果是true
String className=cs.getName();
Constructor[] con=cs.getDeclaredConstructors(); //返回类中的构造方法
Field[] field=cs.getDeclaredFields() ; //返回类中的成员变量
Method[] method=cs.getDeclaredMethods(); //返回类中的方法
System.out.println("类的名字:"+className);
System.out.println("类中有如下的构造方法:");
for(int i=0;i<con.length;i++) {
System.out.println(con[i].toString());
}
System.out.println("类中有如下的成员变量:");
for(int i=0;i<field.length;i++) {
System.out.println(field[i].toString());
}
System.out.println("类中有如下的方法:");
for(int i=0;i<method.length;i++) {
System.out.println(method[i].toString());
}
}
}