Advertisement

java反射技术一篇文章弄懂

阅读量:

前言

反射体现了框架设计的灵活性较高,在我们的Spring框架中,所用到的核心技术和手段便是反射

什么是反射

实现对类各个细节进行组织包装的行为即为反射机制。其优势体现在两个方面:一是能够对这些对象进行动态操作的能力是一个显著的优势;二是通过解耦的方式显著提升了系统的扩展性。

如图所示,在计算机内部经历了几个阶段运行流程。源代码经编译生成.class文件后,则会由类加载器读取.class文件进而进入内存空间中生成对应的Class对象

在这里插入图片描述

获取Class对象的方式

1.class.forName(“全类名”):将字节码文件加载进内存,返回class对象。

  • 多用于配置文件,将类名定义在配置文件中。读取文件,加载类。

2.类名.class:通过类名的属性性class获取。

  • 多用于参数的传递
    3.对象.getclass():getclass()方法在object类中定义着。

  • 多用于对象获取字节码的方式。

复制代码
    public class ReflectDemo1 {
    /** * * class.forName("全类名"):将字节码文件加载进内存,返回class对象。
     * * 类名.class:通过类名的属性性class获取。
     * * 对象.getclass():getclass()方法在object类中定义着。
     * @param args
     */
    public static void main(String[] args) throws Exception {
        //1.lass.forName("全类名")
        Class c = Class.forName("com.nuc.lv.domain.Person");
        System.out.println(c);
        //2.类名.Class
        Class<Person> personClass = Person.class;
        System.out.println(personClass);
        //3.对象名.getClass()
        Person person = new Person();
        Class cls = person.getClass();
        System.out.println(personClass);
        //比较对象
        System.out.println(c == personClass);
        System.out.println(c == cls);
    }
    }
    
    
    java
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-07-13/vqfsEwzMIHhp4PQ1ko2dtlLyDxVg.png)

结论:

Class对象的功能

1.获取成员变量。

  • Field[] getFields() : 获取标记为public的成员字段
  • Field getField()
  • Field[] getDeclaredFields() : 列出所有字段名
  • Field[] getDeclaredField(String name)

2.获取构造方法

  • 构造器集合 getConstructors()
    • 根据指定参数获取构造器 constructor GetConstructor( 类<?>... parameterTypes )
    • 基于指定参数获取声明过的构造器 constructor GetDeclaredConstructor( 类<?>... parameterTypes )
    • 返回基于指定参数的声明过构造器数组 constructor GetDeclaredConstructors()

3.获取成员方法们

  • Methods[] getMethods()
  • Method getMethod(string name,类<?>… parameterTypes)
  • Methods[] getDeclaredMethods()
  • Method getDeclaredMethod(string name,类<?>… parameterTypes)

4.获取类名

  • getName();
在这里插入图片描述
在这里插入图片描述
复制代码
     public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
    
        //获取Person的class对象
        Class cla = Person.class;
        /** * Constructor<?>[] getconstructors()
         * Constructor<T> getconstructor(类<?>... parameterTypes)
         * Constructor<T> getDeclaredconstructor(类<?>... parameterTypes)
         * Constructor<?> [] getDeclaredconstructors()
         */
        Constructor constructor = cla.getConstructor(String.class , int.class);
        System.out.println(constructor);
        Object value1 = constructor.newInstance("张三" , 28);
        System.out.println(value1);
    
        System.out.println("--------");
    
        Constructor constructor1 = cla.getConstructor();
        System.out.println(constructor);
        //创建对象
        Object value2 = constructor1.newInstance();
        System.out.println(value2);
    
        Object o = cla.newInstance();
    
        System.out.println(o);
    }
    
    
    java
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-07-13/OHZ9uPSTMgdwmbN3I8RV7B0CxWUa.png)
复制代码
    public class ReflectDemo4 {
    
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
    
        //获取Person的class对象
        Class cla = Person.class;
        /** * Method[] getMethods()
         * Method getMethod(string name,类<?>... parameterTypes)
         * Method[] getDeclaredMethods()
         * Method getDeclaredMethod(string name,类<?>... parameterTypes)
         */
    
        Method eat_method = cla.getMethod("eat");
        Person person = new Person();
        //执行方法
        eat_method.invoke(person);
    
        //有参数的方法执行
        Method eat_method2 = cla.getMethod("eat",String.class);
        //执行方法
        eat_method2.invoke(person , "鸡腿");
        System.out.println("-------");
    
        // 获取所有public修饰的方法
        Method [] methods = cla.getMethods();
    
        for (Method method : methods){
            System.out.println(method);
            String name = method.getName();
            System.out.println(name);
        }
        //获取类名
        String className = cla.getName();
    
        System.out.println(className);
    }
    }
    
    
    java
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-07-13/oibZHdl5pDwJOGBxk4TV7ILaun0N.png)

结束

反射技术是读懂Spring源码的入门技能,在工作中也会频繁地遇到这一知识点的例子,在实际开发中会经常需要比较两个对象的不同之处。特别是在面试环节同样会频繁出现这一考察点。因此掌握编写代码的能力是学习的重点。

全部评论 (0)

还没有任何评论哟~