zoukankan      html  css  js  c++  java
  • JAVA反射技术的使用

    前言

    在开发html使用jquery提交post的时候,可以使用jquery遍历from元素里面的input元素实现参数组合,这样就不用手动打参数了,特别是在参数很多的时候,费神费时。

    我开发Android提交Http的请求时,经常也会提交一大堆参数,而其中的参数是从相关POJO类的实例获取的,之前一直用手打参数,很麻烦,后面想到以前写c#的时候用到过反射,JAVA应该也会有吧,用反射,遍历实例类的属性,返回参数列表,方便多了。

    原理

    简单记录一下

    User.class.getFields():获得某个类的所有的公共(public)的字段,包括父类中的字段。
    User.class.getDeclaredFields():获得某个类的所有声明的字段,即包括public、private和proteced,但是不包括父类的申明字段。

    field.getName()获取字段的名称

    field.getType()获取字段的声明类型

    getClass().getName() 获得完整的包名和类名

    Class.forName("Reflect.Demo");实例化Class类对象

    Class.forName("Reflect.Person").newInstance();通过Class实例化其他类的对象

    Class.forName("Reflect.Person").getConstructors();取得全部的构造函数

    Class.forName("Reflect.Person").getInterfaces();返回一个类实现的接口

    Class.forName("Reflect.Person").getSuperclass();取得其他类中的父类

    getModifiers()获取修饰符

    getParameterTypes()获取参数类型

    Method method=Class.forName("Reflect.Person").getMethod("sayChina");//调用Person类中的sayChina方法
    method.invoke(Class.forName("Reflect.Person").newInstance());

    调用get,set方法

        /**
         * @param obj
         *            操作的对象
         * @param att
         *            操作的属性
         * */
        public static void getter(Object obj, String att) {
            try {
                Method method = obj.getClass().getMethod("get" + att);
                System.out.println(method.invoke(obj));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     
        /**
         * @param obj
         *            操作的对象
         * @param att
         *            操作的属性
         * @param value
         *            设置的值
         * @param type
         *            参数的属性
         * */
        public static void setter(Object obj, String att, Object value,
                Class<?> type) {
            try {
                Method method = obj.getClass().getMethod("set" + att, type);
                method.invoke(obj, value);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    通过反射操作属性

            Class<?> demo = null;
            Object obj = null;
     
            demo = Class.forName("Reflect.Person");
            obj = demo.newInstance();
     
            Field field = demo.getDeclaredField("sex");
            field.setAccessible(true);
            field.set(obj, "男");

    通过反射取得并修改数组的信息

            int[] temp={1,2,3,4,5};
            Class<?>demo=temp.getClass().getComponentType();
            System.out.println("数组类型: "+demo.getName());
            System.out.println("数组长度  "+Array.getLength(temp));
            System.out.println("数组的第一个元素: "+Array.get(temp, 0));
            Array.set(temp, 0, 100);
            System.out.println("修改之后数组第一个元素为: "+Array.get(temp, 0));

    实现

    了解了原理,实现起来就简单了

      /**
         * 通过反射获取上传参数
         * 
         * @return
         */
        public static RequestParams getParams(Object obj) {
            if (obj == null)
                return null;
            Field[] fields = obj.getClass().getDeclaredFields();
            RequestParams rp = new RequestParams();
            for (int j = 0; j < fields.length; j++) {
                fields[j].setAccessible(true);
                try {
                    if (fields[j].get(obj) == null)
                        continue;
                    else
                        rp.add(fields[j].getName(), String.valueOf(fields[j].get(obj)));
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
    
            return rp;
        }

    关于field还有一种情况我们需要注意,就是当字段修饰符为private时,我们需要加上:

    field.setAccessible(true);

    参考:

    http://blog.csdn.net/z_l_l_m/article/details/8217007

    http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html

  • 相关阅读:
    Salesforce 大量数据部署的最佳实践
    Salesforce 数据备份和恢复小知识
    Salesforce 导入导出数据简介
    GDPR 和个人信息保护的小知识
    代码审查要点简介
    Salesforce 外部对象
    Python scipy.sparse.csr_matrix()[csc_matrix()]
    Deep Compression
    Pascal voc api
    Python内置模块-xml模块
  • 原文地址:https://www.cnblogs.com/leestar54/p/4285169.html
Copyright © 2011-2022 走看看