JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的以及动态调用对象的方法的功能称为java语言的反射机制。
Java反射机制主要提供了以下功能:在运行时判定任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判定任意一个类所具有的成员变量和方法;在运行时调用任意一个对象的方法;生成动态代理。
反射常用的API,代码中总结:- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;
-
- public class ReflectDemo2 {
-
- /**
- * @author YCY
- */
- public static void main(String[] args) {
- Class testClass;
- try {
- // 拿到Test字节码文件
- testClass = Class.forName("com.java.Test");
- // 获取Test包
- Package p = testClass.getPackage();
- // 创建Test对象
- Test test1 = (Test) testClass.newInstance();
- // 调用Test对象中的public方法
- test1.method1();
- test1.method3(1, '你');
- // 获取Test全部的构造方法
- Constructor<?> cons[] = testClass.getConstructors();
- // 遍历数组,打印出Test所有的构造方法
- for (int i = 0; i < cons.length; i++) {
- System.out.println(cons[i]);
- }
- // 通过有参构造方法创建Test对象
- Test test2 = (Test) cons[0].newInstance(1, "你好", '吗');
- // 获取Test类继承的父类以及实现的接口
- Class<?> parents = testClass.getSuperclass();
- // 打印出Test类的父类名称
- System.out.println(parents.getName());
- // 获取Test类的所有实现的接口
- Class<?>[] interfaces = testClass.getInterfaces();
- for (int i = 0; i < interfaces.length; i++) {
- System.out.println(interfaces[i].getName());
- }
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- }
-
- }
复制代码
|