zoukankan      html  css  js  c++  java
  • Java反射机制概念及应用场景

    Java的反射机制相信大家在平时的业务开发过程中应该很少使用到,但是在一些基础框架的搭建上应用非常广泛,今天简单的总结学习一下。

    1. 什么是反射机制?

    Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的以及动态调用对象的方法的功能称为Java的反射机制。

    通俗理解:通过反射,任何类对我们来说都是透明的,想要获取任何东西都可以,破坏程序安全性?

    先来看看反射机制都提供了哪些功能。

    2. 反射机制能够获取哪些信息?

    在运行时判定任意一个对象所属的类;
    在运行时构造任意一个类的对象;
    在运行时判定任意一个类所具有的成员变量和方法;
    在运行时调用任意一个对象的方法;
    生成动态代理;

    主要的反射机制类:

    java.lang.Class; //类               
    java.lang.reflect.Constructor;//构造方法 
    java.lang.reflect.Field; //类的成员变量       
    java.lang.reflect.Method;//类的方法
    java.lang.reflect.Modifier;//访问权限
    2.1 class对象的获取
    //第一种方式 通过对象getClass方法
    Person person = new Person();
    Class<?> class1 = person.getClass();
    //第二种方式 通过类的class属性
    class1 = Person.class;
    try {
        //第三种方式 通过Class类的静态方法——forName()来实现
        class1 = Class.forName("club.sscai.Person");
    catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    上边这三种方式,最常用的是第三种,前两种获取 class 的方式没有什么意义,毕竟你都导了包了。

    2.2 获取class对象的属性、方法、构造函数等
    Field[] allFields = class1.getDeclaredFields();//获取class对象的所有属性
    Field[] publicFields = class1.getFields();//获取class对象的public属性
    try {
        Field ageField = class1.getDeclaredField("age");//获取class指定属性
        Field desField = class1.getField("des");//获取class指定的public属性
    catch (NoSuchFieldException e) {
        e.printStackTrace();
    }

    Method[] methods = class1.getDeclaredMethods();//获取class对象的所有声明方法
    Method[] allMethods = class1.getMethods();//获取class对象的所有方法 包括父类的方法

    Class parentClass = class1.getSuperclass();//获取class对象的父类
    Class<?>[] interfaceClasses = class1.getInterfaces();//获取class对象的所有接口

    Constructor<?>[] allConstructors = class1.getDeclaredConstructors();//获取class对象的所有声明构造函数
    Constructor<?>[] publicConstructors = class1.getConstructors();//获取class对象public构造函数
    try {
        Constructor<?> constructor = class1.getDeclaredConstructor(new Class[]{String.class});//获取指定声明构造函数
        Constructor publicConstructor = class1.getConstructor(new Class[]{});//获取指定声明的public构造函数
    catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

    Annotation[] annotations = class1.getAnnotations();//获取class对象的所有注解
    Annotation annotation = class1.getAnnotation(Deprecated.class);//获取class对象指定注解

    Type genericSuperclass = class1.getGenericSuperclass();//获取class对象的直接超类的 Type
    Type[] interfaceTypes = class1.getGenericInterfaces();//获取class对象的所有接口的type集合
    2.3 反射机制获取泛型类型

    示例:

    //People类public class People<T> {}
    //Person类继承People类public class Person<Textends People<Stringimplements PersonInterface<Integer> {}
    //PersonInterface接口public interface PersonInterface<T> {}

    获取泛型类型:

    Person<String> person = new Person<>();
    //第一种方式 通过对象getClass方法
    Class<?> class1 = person.getClass();
    Type genericSuperclass = class1.getGenericSuperclass();//获取class对象的直接超类的 Type
    Type[] interfaceTypes = class1.getGenericInterfaces();//获取class对象的所有接口的Type集合
    getComponentType(genericSuperclass);
    getComponentType(interfaceTypes[0]);

    getComponentType具体实现

    private Class<?> getComponentType(Type type) {
    Class<?> componentType = null;
    if (type instanceof ParameterizedType) {
        //getActualTypeArguments()返回表示此类型实际类型参数的 Type 对象的数组。
        Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
        if (actualTypeArguments != null && actualTypeArguments.length > 0) {
        componentType = (Class<?>) actualTypeArguments[0];
        }
    else if (type instanceof GenericArrayType) {
        // 表示一种元素类型是参数化类型或者类型变量的数组类型
        componentType = (Class<?>) ((GenericArrayType) type).getGenericComponentType();
    else {
        componentType = (Class<?>) type;
    }
    return componentType;
    }
    2.4 通过反射机制获取注解信息(知识点)

    这种场景,经常在 Aop 使用,这里重点以获取Method的注解信息为例。

    try {
        //首先需要获得与该方法对应的Method对象
        Method method = class1.getDeclaredMethod("jumpToGoodsDetail"new Class[]{String.classString.class});
        Annotation[] annotations1 = method.getAnnotations();//获取所有的方法注解信息
        Annotation annotation1 = method.getAnnotation(RouterUri.class);//获取指定的注解信息
        TypeVariable[] typeVariables1 = method.getTypeParameters();
        Annotation[][] parameterAnnotationsArray = method.getParameterAnnotations();//拿到所有参数注解信息
        Class<?>[] parameterTypes = method.getParameterTypes();//获取所有参数class类型
        Type[] genericParameterTypes = method.getGenericParameterTypes();//获取所有参数的type类型
        Class<?> returnType = method.getReturnType();//获取方法的返回类型
        int modifiers = method.getModifiers();//获取方法的访问权限
    catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

    3. 反射机制的应用实例

    大家是不是经常遇到一种情况,比如两个对象,Member 和 MemberView,很多时候我们都有可能进行相互转换,那么我们常用的方法就是,把其中一个中的值挨个 get 出来,然后再挨个 set 到另一个中去,接下来我介绍的这种方法就可以解决这种问题造成的困扰:

    public class TestClass{

        public double eachOrtherToAdd(Integer one,Double two,Integer three){
            return one + two + three;
        }
    }

    public class ReflectionDemo{

        public static void main(String args[]){
            String className = "initLoadDemo.TestClass";
            String methodName = "eachOrtherToAdd";
            String[] paramTypes = new String[]{"Integer","Double","int"};
            String[] paramValues = new String[]{"1","4.3321","5"};

            // 动态加载对象并执行方法
            initLoadClass(className, methodName, paramTypes, paramValues);

        }

        @SuppressWarnings("rawtypes")
        private static void initLoadClass(String className,String methodName,String[] paramTypes,String[] paramValues){
            try{
                // 根据calssName得到class对象
                Class cls = Class.forName(className);

                // 实例化对象
                Object obj = cls.newInstance();

                // 根据参数类型数组得到参数类型的Class数组
                Class[] parameterTypes = constructTypes(paramTypes);

                // 得到方法
                Method method = cls.getMethod(methodName, parameterTypes);

                // 根据参数类型数组和参数值数组得到参数值的obj数组
                Object[] parameterValues = constructValues(paramTypes,paramValues);

                // 执行这个方法并返回obj值
                Object returnValue = method.invoke(obj, parameterValues);

                System.out.println("结果:"+returnValue);

            }catch (Exception e){
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        private static Object[] constructValues(String[] paramTypes,String[] paramValues){
            Object[] obj = new Object[paramTypes.length];
            for (int i = 0; i < paramTypes.length; i++){
                if(paramTypes[i] != null && !paramTypes[i].trim().equals("")){
                    if ("Integer".equals(paramTypes[i]) || "int".equals(paramTypes[i])){
                        obj[i] = Integer.parseInt(paramValues[i]);
                    }else if ("Double".equals(paramTypes[i]) || "double".equals(paramTypes[i])){
                        obj[i] = Double.parseDouble(paramValues[i]);
                    }else if ("Float".equals(paramTypes[i]) || "float".equals(paramTypes[i])){
                        obj[i] = Float.parseFloat(paramValues[i]);
                    }else{
                        obj[i] = paramTypes[i];
                    }
                }
            }
            return obj;
        }

        @SuppressWarnings("rawtypes")
        private static Class[] constructTypes(String[] paramTypes){
            Class[] cls = new Class[paramTypes.length];
            for (int i = 0; i < paramTypes.length; i++){
                if(paramTypes[i] != null && !paramTypes[i].trim().equals("")){
                    if ("Integer".equals(paramTypes[i]) || "int".equals(paramTypes[i])){
                        cls[i] = Integer.class;
                    }else if ("Double".equals(paramTypes[i]) || "double".equals(paramTypes[i])){
                        cls[i] = Double.class;
                    }else if ("Float".equals(paramTypes[i]) || "float".equals(paramTypes[i])){
                        cls[i] = Float.class;
                    }else{
                        cls[i] = String.class;
                    }
                }
            }
            return cls;
        }
    }

    4. 总结:

    文章开头也有提到,平时的业务开发者中反射机制是比较少用到的,但是,总归要学习的,万一哪天用到了呢?

    反射机制的优缺点:

    优点:
    运行期类型的判断,动态类加载,动态代理使用反射。


    缺点:
    性能是一个问题,反射相当于一系列解释操作,通知jvm要做的事情,性能比直接的java代码要慢很多。

    关于Java反射机制,需要明确几点,反射到底是个怎么过程?反射的实际应用场景又有哪些?

    前面JVM类加载机制时有张图,拿来改造改造:

    如果文章有错的地方欢迎指正,大家互相留言交流。习惯在微信看技术文章,想要获取更多的Java资源的同学,可以关注微信公众号:niceyoo

  • 相关阅读:
    echarts各个配置项详细说明总结
    享元模式
    观察者模式
    策略模式
    桥接模式
    适配器模式
    建造者模式
    原型模式
    单例模式
    Java8新特性——集合底层源码实现的改变
  • 原文地址:https://www.cnblogs.com/niceyoo/p/10590841.html
Copyright © 2011-2022 走看看