Java基础整理——超级简单的理解java反射

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

一、什么是反射

程序在运行时,动态的去获取类的信息、加载类、创建对象、操作类或方法和属性。

  1. 获取类对象,也就知道这个类的信息(定义什么方法、属性、类名等)
  2. 可以构造这个类的实例、可以操作这个类对象的某个方法或属性

说人话就是,你不new 对象了,一样有对象,随意玩弄。嘿嘿~

二、反射的使用

废话不多说,最容易理解的就是自己去操作一遍反射的操作~

1.定义一个类

我给了两个构造,一个无参构造、一个有参构造

定义一个类:
public class ReflectionDemo {
    public String username;
    private Integer password ;
    
    public ReflectionDemo() {

    }
    public ReflectionDemo(String name) {
        System.out.println(name);
    }
    public void say() {
        System.out.println("hello!");
    }

    public void talk(String name, Integer age) {
        System.out.println(name + "今年:" + age + "岁!");
    }
}

2.获取类对象的三种方式

 //1.通过对象的getClass()方法获取
 ReflectionDemo rd = new ReflectionDemo();
 Class<? extends ReflectionDemo> aClass = rd.getClass();
 System.out.println("通过对象的getClass()方法获取:"+aClass);
 //2.通过类名的class
 Class<? extends ReflectionDemo> aClass1 = ReflectionDemo.class;
 System.out.println("通过类名的class: "+aClass1);
 //3.通过Class.forName()
 try {
     Class<?> aClass2 = Class.forName("com.my.reflection.ReflectionDemo");
     System.out.println("Class.forName():"+aClass2);
 } catch (ClassNotFoundException e) {
     e.printStackTrace();
 }

运行结果:

通过对象的getClass()方法获取:class com.my.reflection.ReflectionDemo
通过类名的class: class com.my.reflection.ReflectionDemo
Class.forName():class com.my.reflection.ReflectionDemo

3.获取属性

 /**
             * 反射 获取成员变量
             * Field getField(String name)  根据变量名,返回一个具体的具有public属性的成员变量
             * Field[] getFields()  返回具有public属性的成员变量的数组
             * Field getDeclaredField(String name) 根据变量名,返回一个成员变量(不分public和非public属性)
             * Field[] getDelcaredFields() 返回所有成员变量组成的数组(不分public和非public属性)
             */
            Class class4 = null;
            try {
                //获取类对象
                class4 = Class.forName("com.my.reflection.ReflectionDemo");
                //获取属性
                Field field1 = class4.getField("username");
                System.out.println("field1=" + field1.getName());
                Field field2 = class4.getDeclaredField("password");
                System.out.println("field2=" + field2.getName());
                System.out.println("*******************");
                // 使用getFields获取属性
                Field[] fields = class4.getFields();
                for (Field f : fields) {
                    System.out.println(f);
                }
                System.out.println("*******************");
                // 使用getDeclaredFields获取属性
                fields = class4.getDeclaredFields();
                for (Field f : fields) {
                    System.out.println(f);
                }

运行结果:

field1=username
field2=password
*******************
public java.lang.String com.my.reflection.ReflectionDemo.username
*******************
public java.lang.String com.my.reflection.ReflectionDemo.username
private java.lang.Integer com.my.reflection.ReflectionDemo.password

4.获取类的方法

/**
* 反射 调用 对象方法
* Method getMethod(String name, Class[] params) 根据方法名和参数,返回一个具体的具有public属性的方法
* Method[] getMethods() 返回所有具有public属性的方法数组
* Method getDeclaredMethod(String name, Class[] params)  根据方法名和参数,返回一个具体的方法(不分public和非public属性)
* Method[] getDeclaredMethods() 返回该类中的所有的方法数组(不分public和非public属性)
*/
Class class3 = null;
try {
       class3 = Class.forName("com.my.reflection.ReflectionDemo");
       Method method = class3.getMethod("talk", String.class,Integer.class);
       Object object = class3.newInstance();
       method.invoke(object, "老王",18);
   } catch (ClassNotFoundException e) {
       e.printStackTrace();
   } catch (NoSuchMethodException e) {
       e.printStackTrace();
   } catch (IllegalAccessException e) {
       e.printStackTrace();
   } catch (InstantiationException e) {
       e.printStackTrace();
   } catch (InvocationTargetException e) {
       e.printStackTrace();
   }

运行结果:

运行结果:

老王今年:18岁!

5.获取类的Constructor并创建对象

       /**
        * 反射通过无惨构造实例对象
        */
        Class class1 = null;
        try {
            class1 = Class.forName("com.my.reflection.ReflectionDemo");
            Object object = class1.newInstance();
            ReflectionDemo reflectionDemo = (ReflectionDemo) object;
            reflectionDemo.say();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

        /**
         * 反射通过构造实例对象
         * Constructor getConstructor(Class[] params)根据构造函数的参数,返回一个具体的具有public属性的构造函数
         * Constructor getConstructors()     返回所有具有public属性的构造函数数组
         * Constructor getDeclaredConstructor(Class[] params)     根据构造函数的参数,返回一个具体的构造函数(不分public和非public属性)
         * Constructor getDeclaredConstructors()    返回该类中所有的构造函数数组(不分public和非public属性)
         */
        Class class2 = null;
        try {
            class2 = Class.forName("com.my.reflection.ReflectionDemo");
            Constructor constructor = class2.getConstructor(String.class);
            Object object = constructor.newInstance("abc");
            ReflectionDemo reflectionDemo = (ReflectionDemo) object;
            reflectionDemo.say();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

运行结果:

运行结果

hello!
abc
hello!

总结

本章主要内容:

  1. 弄明白反射是啥
  2. 利用反射获取类对象,操作类的方法和属性,以及创建对象。
posted @ 2019-09-15 09:53  笑里笑外~  阅读(207)  评论(0编辑  收藏  举报