• java的反射Method


    开发过程中有时会使用到动态生成一个class,记录下,方便后面开发直接参考

    1.在一个bean类中通过反射动态获取调用setter和getter方法

    /**
    *获取类的方法
    */
    public static Method getGetOrSetMethod(Object obj, String fieldName, Boolean isGetMethod, Class<?> fieldType) throws SecurityException, NoSuchMethodException{
            Method method=null;
            String methodName;
            if(isGetMethod != null && isGetMethod){
                methodName = "get";
            }else{
                methodName = "set";
            }
            if(DataUtil.isUppercaseLetter(fieldName, 1)){
                methodName += fieldName;
            }else{
                methodName += fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            }
    
            if(fieldType != null){
                method = obj.getClass().getDeclaredMethod(methodName, fieldType);
            }else{
                method = obj.getClass().getDeclaredMethod(methodName);
            }
            return method;
        }
    /**
    *给字段设值
    */
    
    public static void setFieldValue(Object obj, String fieldName, Object value, Class<?> fieldType) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException{
            Method setMethod = getGetOrSetMethod(obj, fieldName, null, fieldType);
            if(fieldType != value.getClass()){    //value的类型和set方法中的参数类型不一致的时候
                if(fieldType == Double.class){    //Object-->Double
                    value = getDoubleValue(value);
                }
            }
            setMethod.invoke(obj, value);
        }
    /**
    *获取字段的值
    */
    public static Object getFiledValue(Object obj, String fieldName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException{
            Object result=null;
            Method getMethod = getGetOrSetMethod(obj, fieldName, true, null);
            if(getMethod != null){
                result = getMethod.invoke(obj);
            }
            return result;
        }
    /**
    *获取字段的值
    */
    public Object getDeclaredField(String name){
            Object obj=null;
            try {
                obj=类名.class.getDeclaredField(name).get(this);
            } catch (Exception e) {}
            return obj;
        }

    /**
    * 获取Double型数据
    * */
    public static Double getDoubleValue(Object obj){
    Double value = null;
    if(obj != null){
    if(obj.getClass() == Double.class){
    value=(Double)obj;
    }else if(obj.getClass() == Long.class){
    value = ((Long)obj).doubleValue();
    }else if(obj.getClass() == Integer.class){
    value = ((Integer)obj).doubleValue();
    }
    }
    return value;
    }
     

    2.使用cglib工具包动态生成bean

    给出一个demo

    mvn依赖:

    <dependency>
         <groupId>cglib</groupId>
         <artifactId>cglib</artifactId>
         <version>2.2.2</version>
    </dependency>            

    公共bean类

    public class CreatedBean {
        //Bean实体Object
        public Object object = null;
        //属性map
        public BeanMap beanMap = null;
    
        public CreatedBean() {
            super();
        }
    @SuppressWarnings(
    "unchecked") public CreatedBean(Map<String, Class> propertyMap) { //用一组属性生成实体Bean this.object = generateBean(propertyMap); //用实体Bean创建BeanMap,以便可以设置和获取Bean属性的值 this.beanMap = BeanMap.create(this.object); } /** * 给bean中的属性赋值 * * @param property 属性名 * @param value 值 */ public void setValue(String property, Object value) { beanMap.put(property, value); } /** * 获取bean中属性的值 * * @param property 属性名 * @return*/ public Object getValue(String property) { return beanMap.get(property); } /** * 得到该实体bean对象 * * @return */ public Object getObject() { return this.object; } @SuppressWarnings("unchecked") private Object generateBean(Map<String, Class> propertyMap) { //根据一组属性名和属性值的类型,动态创建Bean对象 BeanGenerator generator = new BeanGenerator(); Set keySet = propertyMap.keySet(); for (Iterator i = keySet.iterator(); i.hasNext();) { String key = (String) i.next(); generator.addProperty(key, (Class) propertyMap.get(key)); } return generator.create(); //创建Bean } }

    测试调用公共bean

     public static void main(String[] args) throws Exception {
            HashMap<String, Class> propertyMap = new HashMap<String, Class>();
            propertyMap.put("id", Class.forName("java.lang.Integer"));
            propertyMap.put("name", Class.forName("java.lang.String"));
            propertyMap.put("address", Class.forName("java.lang.String")); // 生成动态Bean
            propertyMap.put("date", Class.forName("java.sql.Date"));
            CreatedBean bean = new CreatedBean(propertyMap);
            // 给Bean设置值
            bean.setValue("id", 123);  //Auto-boxing
            bean.setValue("name", "454");
            bean.setValue("address", "789");
    
            // 获得bean的实体
            Object object = bean.getObject();
            // 通过反射查看所有方法名
            Class clazz = object.getClass();
            Method[] methods = clazz.getDeclaredMethods();
            for (Method curMethod : methods) {
                System.out.println(curMethod.getName());
            }
            System.out.println(" >> id = " + bean.getValue("id"));
            System.out.println(" >> name = " + bean.getValue("name"));
            System.out.println(" >> address = " + bean.getValue("address"));
        }
  • 相关阅读:
    【转】使用Javascript改变HTML内容 拓荒者
    【转】ASP.NET MVC 过滤器Filter 拓荒者
    【转】JavaScript简介 拓荒者
    edge.js架起node.js和.net互操作桥梁
    利用Node.js为Node.js生成HttpStatusCode辅助类并发布到npm
    nodejs上HTML分析利器nodejquery
    JavaScript 函数replace揭秘
    利用Node.js本地构建
    Angularjs的IOC Inject分析
    团队文化中的害群之马
  • 原文地址:https://www.cnblogs.com/zyanrong/p/12738837.html
Copyright © 2020-2023  润新知