Java反射机制概念及应用场景

Java的反射机制相信你们在平时的业务开发过程当中应该不多使用到,可是在一些基础框架的搭建上应用很是普遍,今天简单的总结学习一下。java

1. 什么是反射机制?

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

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

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

2. 反射机制可以获取哪些信息?

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

主要的反射机制类:app

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 反射机制获取泛型类型

示例:jvm

//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

相关文章
相关标签/搜索