Java的反射(reflection)机制是指在程序的运行状态中,可以构造任意一个类的对象,可以了解任意一个对象所属的类,可以了解任意一个类的成员变量和方法,可以调用任意一个对象的属性和方法。这种动态获取程序信息以及动态调用对象的功能称为Java语言的反射机制。反射被视为动态语言的关键。
Java反射机制主要提供了以下功能: 在运行时判断任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法;在运行时调用任意一个对象的方法;生成动态代理
反射机制所需的类主要有java.lang包中的Class类和java.lang.reflect包中的Constructor类、Field类、Method类和Parameter类。
一,创建的项目和包名,类名如下:
二,获取Class类
new之后使用getClass()获取Class对象
Student stu1 = new Student();//这一new 产生一个Student对象,一个Class对象。
Class stuClass = stu1.getClass();//获取Class对象
使用静态的class属性获取
Class stuClass2 = Student.class;//使用静态的class属性获取
通过Class类的forName()方法获取常用
Class stuClass3 = Class.forName("com.bean.Student");//括号中是类的全类名(即包名+类名)
三,在测试类Class中的一些常用的方法
public class Test01 {
public static void main(String[] args) throws Exception {
//通过全类名加载类的Class对象
Class cla = Class.forName("com.service.impl.BookServiceImpl");
//Class对象可以认为是类的手术刀,可以解刨类里面的东西--属性、构造器、方法
Field[] fields = cla.getFields(); //只能获取public修饰的属性
for (Field field : fields) {
System.out.println(field);
}
System.out.println("-------------");
Field[] fields1 = cla.getDeclaredFields(); //获取所有属性
for (Field field : fields1) {
System.out.println(field);
}
System.out.println("======================");
Constructor[] constructors = cla.getConstructors();//获取构造该方法(public修饰的方法)
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
System.out.println("-------------");
Constructor[] constructors1 = cla.getDeclaredConstructors();//获取所有的构造方法
for (Constructor constructor : constructors1) {
System.out.println(constructor);
}
System.out.println("======================");
Method[] methods = cla.getMethods();//获取所有public修饰的方法
for (Method method : methods) {
System.out.println(method);
}
System.out.println("-------------");
Method[] methods1 = cla.getDeclaredMethods();//获得类的所有方法。包括private 声明的和继承类
for (Method method : methods1) {
System.out.println(method);
}
}
}