1、reflect的定义
JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制.
2、reflect的抽象分析,具体如下:
1)、对类的分析,抽象为class对象
2)、对构造方法的分析,抽象为Constructor类的对象
3)、对成员变量的分析,抽象为Field类的对象
4)、对方法的分析,抽象为Method类的对象
3、reflect机制简单实例
1)、定义Computer.java类
package cn.java.example;
public class Computer {
private String cpuType;
private int memory;
private String display;
public String getCpuType() {
return cpuType;
}
public void setCpuType(String cpuType) {
this.cpuType = cpuType;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
public String getDisplay() {
return display;
}
public void setDisplay(String display) {
this.display = display;
}
}
2)、反射测试类
package cn.java.example;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestReflect {
public static void main(String[] args) {
Class<Computer> clazz=Computer.class;
try {
//获得Computer类的cpuType属性对象
Field field=clazz.getDeclaredField("cpuType");
System.out.println(field.getName());
System.out.println(field.getType());
System.out.println(field.getModifiers());
System.out.println("/********************/");
Field[] fieldAll=clazz.getDeclaredFields();
//遍历所有的属性
for (Field field2 : fieldAll) {
System.out.println(field2.getName());
System.out.println(field2.getType());
System.out.println(field2.getModifiers());
}//for
System.out.println("/********************/");
//为thinkPad没有设置的memory赋值
Computer thinkPad=new Computer();
Field memory=clazz.getDeclaredField("memory");
memory.setAccessible(true);//取消对memory属性的修饰符的检查访问,以便为memory属性赋值
memory.setInt(thinkPad, 500);
memory.setAccessible(false);回复对memory属性的修饰符的检查访问
System.out.println("My thinkPad memory is "+thinkPad.getMemory()+"G");
System.out.println("/********************/");
//method获取的方法
Method method=clazz.getDeclaredMethod("getCpuType");
System.out.println(method.getName());
System.out.println(method.getModifiers());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}