Java一反射

目录

一、什么是反射

二、反射的作用和应用场景

三、反射的优缺点

四、使用反射(获取Class对象、获取类的构造方法及其参数类型和修饰类型、通过构造函数的newInstance方法创建类的实例、获取类的方法并调用它、获取和修改类的属性 等等)

五、反射问题探索


一、什么是反射

Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类中的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。通俗点讲,通过反射,该类对我们来说是完全透明的,想要获取任何东西都可以。

二、反射的作用和应用场景

作用

  • 获取任意类的名称、package 信息、所有属性、方法、注解、类型、类加载器、modifiers、父类、现实接口等
  • 获取任意对象的属性,并且能改变对象的属性
  • 调用任意对象的方法
  • 判断任意一个对象所属的类
  • 实例化任意一个类的对象
  • 生成动态代理。

应用场景

1.实例化系统隐藏的类
2.调用对象被隐藏起来的属性和方法
3.动态代理
4.与注解的结合使用
5.在编译时无法知道该对象或类可能属于哪些类,程序在运行时获取对象和类的信息

反射的作用和应用场景有点类似了,我们只要记住反射的作用,就能在你遇到问题的时候想起它。反射一般是用来开发框架,在我们平常的开发中,反射用得并不多,但是我们必须搞懂它,它可以帮助我们理解一些框架的原理,有一句很经典的话就是:反射是框架设计的灵魂

三、反射的优缺点

优点

提高了 Java 程序的灵活性和扩展性,降低耦合性,提高自适应能力。
允许程序创建和控制任何类的对象,无需提前硬编码目标类
应用很广,测试工具、框架都用到了反射

缺点

性能问题:反射是一种解释操作,远慢于直接代码。因此反射机制主要用在对灵活性和扩展性要求很高的系统框架上,普通程序不建议使用
模糊程序内部逻辑:反射绕过了源代码,无法再源代码中看到程序的逻辑,会带来维护问题
增大了复杂性:反射代码比同等功能的直接代码更复杂

四、使用反射

1、获取Class类对象,三种方式

 //通过Class.forName()方法获取
        try {
            Class test = Class.forName("com.mumumxi.test");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

//通过对象的getClass()方法获取
        String string = "test";
        Class test1 = string.getClass();

//直接通过类字面常量获取
        Class test2 = String.class;
      

2、获取类的构造方法及其参数类型和修饰语

package com.mumuxi.testapplication;


import java.lang.reflect.Constructor;


/**
 * @author mumuxi
 * @date 2020/1/19
 */
public class Test {

    public static final String TAG = Test.class.getSimpleName();

    public Test() {
    }

    public Test(int i) {
    }

    public Test(int i, String string) {
    }

    public static void main(String[] args) {

        Class test = null;

        try {
            test = Class.forName("com.mumuxi.testapplication.Test");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //getDeclaredConstructors 返回类的所有构造函数,包括私有的
        Constructor[] constructors = test.getDeclaredConstructors();

        for (Constructor constructor : constructors) {
            //通过getParameterTypes 获取构造函数的参数Class列表
            for (Class name : constructor.getParameterTypes()) {
                System.out.println(name.getName());
            }

            //通过getModifiers获取构造函数的修饰类型,是private的还是public..
            System.out.println(constructor.getModifiers());
            System.out.println("--------------------------------");

        }

        //getConstructors 返回public类型的构造函数
        Constructor[] constructors1 = test.getConstructors();


        //获取无参的构造函数
        try {
            Constructor constructor = test.getDeclaredConstructor();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        //获取只有一个参数的构造函数,参数类型是int
        Class[] classes = {int.class};
        try {
            Constructor constructor1 = test.getDeclaredConstructor(classes);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        //获取只有两个参数的构造函数,参数类型依次是int 、String
        Class[] classes1 = {int.class, String.class};
        try {
            Constructor constructor1 = test.getDeclaredConstructor(classes1);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }

}




3、通过构造函数的newInstance方法创建类的实例

package com.mumuxi.testapplication;


import android.util.Log;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author mumuxi
 * @date 2020/1/19
 */
public class Test {

    public static final String TAG = Test.class.getSimpleName();

    public Test() {

    }

    public Test(int i) {

    }

    public Test(int i, String string) {

    }

    public static void main(String[] args) {
        Class test = null;

        try {
            test = Class.forName("com.mumuxi.testapplication.Test");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Constructor constructor = null;

        //调用无参构造函数新建类的实例
        if (test != null) {
            try {
                constructor = test.getDeclaredConstructor();
                constructor.setAccessible(true);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        if (constructor != null) {
            try {
                Object object = constructor.newInstance();
                if (object instanceof Test) {
                    System.out.println("create object success");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        //调用含有一个参数的构造函数新建类的实例
        Class[] param = {int.class};
        if (test != null) {
            try {
                constructor = test.getDeclaredConstructor(param);
                constructor.setAccessible(true);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        if (constructor != null) {
            try {
                Object object = constructor.newInstance(1);
                if (object instanceof Test) {
                    System.out.println("create object success");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        //调用含有两个参数的构造函数新建类的实例
        Class[] param1 = {int.class, String.class};
        if (test != null) {
            try {
                constructor = test.getDeclaredConstructor(param1);
                constructor.setAccessible(true);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        if (constructor != null) {
            try {
                Object object = constructor.newInstance(1, "hehe");
                if (object instanceof Test) {
                    System.out.println("create object success");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    }

}



4、获取类的方法并调用它(私有、公共、静态)

package com.mumuxi.testapplication;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author mumuxi
 * @date 2020/1/19
 */
public class Test {
    
    private static final String TAG = Test.class.getSimpleName();
    
    public static void main(String[] args) {

        Test test = new Test();
        Method method = null;

        //获取一个对象的私有或公共方法并调用它
        try {
            /*通过Class对象的getDeclaredMethod方法获取指定方法,
            第一个参数是方法名,第二个参数是方法的参数Class对象列表*/
            method = Test.class.getDeclaredMethod("test", null);
            //method 是私有类型的还需要通过setAccessible给予权限
            method.setAccessible(true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        if (method != null) {
            try {
                //通过invoke来执行该方法第,一个参数是类实例,第二个是方法的参数列表
                method.invoke(test, null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }


        //获取指定类的私有方法并调用它
        try {
            method = Test.class.getDeclaredMethod("test1");
            //method 是私有类型的还需要通过setAccessible给予权限
            method.setAccessible(true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        if (method != null) {
            try {
                //通过invoke来执行该方法第,一个参数是类实例,第二个是方法的参数列表
                method.invoke(null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    }

    private void test() {
        System.out.println("hehe");
    }

    public static void test1(){
        System.out.println("hehe1");
    }
}

5、获取和修改类的属性 (私有、公共、静态)

package com.mumuxi.testapplication;

import java.lang.reflect.Field;


/**
 * @author mumuxi
 * @date 2020/1/19
 */
public class Test {

    public static final String TAG = Test.class.getSimpleName();

    private String test = "test";
    private static String TEST = "TEST";

    public static void main(String[] args) {


        Class test = null;

        try {
            test = Class.forName("com.mumuxi.testapplication.Test");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //获取实例的指定字段并修改它的值
        Object object = null;

        if (test != null) {
            try {
                object = test.newInstance();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }


        Field field = null;
        if (test != null) {
            try {
                //通过Class对象的getDeclaredField获取指定属性,参数是属性名
                field = test.getDeclaredField("test");
                field.setAccessible(true);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }


        if (field != null && object != null) {
            try {
                //通过Field的get方法获取指定实例的字段,参数是具体的实例
                Object fieldObject = field.get(object);
                System.out.println("非静态字段------------");
                if (fieldObject instanceof String) {
                    System.out.println("String 类型");
                }
                System.out.println(fieldObject);

                /*通过Field的set方法修改指定实例的字段
                 第一个参数是具体的实例,第二个参数是需要修改的值*/
                field.set(object, "改掉了");
                System.out.println(field.get(object));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        //修改类的静态字段
        if (test != null) {
            try {
                //通过Class对象的getDeclaredField获取指定属性,参数是属性名
                field = test.getDeclaredField("TEST");
                field.setAccessible(true);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        try {
            System.out.println("静态字段------------");
            Object staticObject = field.get(null);
            System.out.println(staticObject);
            field.set(staticObject, "ABCD");
            System.out.println(field.get(null));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

}

6、通过Class对象getSuperclass方法的获取类的父类

       Class test = null;

        try {
            test = Class.forName("com.mumuxi.testapplication.Test");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        if (test != null) {
            Class superClass = test.getSuperclass();
        }

7、获取类的接口

Class test = null;

        try {
            test = Class.forName("com.mumuxi.testapplication.Test");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        if (test != null) {
            Class[] interfaces = test.getInterfaces();
        }

推荐使用 Joor反射库 ,可以参考Java反射库jOOR简介

五、反射问题探索

1.Java中的final字段真的不能修改么?(怎样修改final字段)
通过反射是可以修改final字段的!但是一般情况下不建议这么做,如果出现问题也比较难排查。
具体可以参考:https://blog.csdn.net/adu003/article/details/104376399

2.反射可以破坏单例吗?
反射可以破坏单例,但是我们也可以通过一些方法防御被反射破坏单例。

3.反射的优缺点

优点:

1.能够运行时动态地获取类的实例,提高灵活性

2.与动态编译结合

缺点:
1)使用反射性能较低,需要解析字节码,将内存中的对象进行解析。
解决方案:
1、通过setAccessible(true)关闭JDK的安全检查来提升反射速度;
2、多次创建一个类的实例时,有缓存会快很多
3、ReflflectASM工具类,通过字节码生成的方式加快反射速度
2)相对不安全,破坏了封装性(因为通过反射可以获得私有方法和属性)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容