java通过cglib动态生成实体bean

java通过cglib动态生成实体beanDynamicBeanEntity.class动态bean类:packagecom.dym.entity;importnet.sf.cglib.beans.BeanGenerator;importorg.apache.commons.collections.map.MultiValueMap;importjava.lang.reflect.*;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.It

大家好,又见面了,我是你们的朋友全栈君。

maven依赖:

        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>
		<dependency>
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-databind</artifactId>
		    <version>2.12.5</version>
		</dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>3.2.4</version>
        </dependency>

DynamicBeanEntity.class动态bean类:

package com.supcon.mare.tankinfo.controller.vo;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.sf.cglib.beans.BeanGenerator;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author: zhaoxu
 * @description:
 */
@Data
@NoArgsConstructor
public class DynmicVO { 
   

    Object dynamicBean;

    private static ObjectMapper objectMapper = new ObjectMapper();

    Class clazz;

    public DynmicVO(Map dynAttrMap) { 
   
        this.dynamicBean = generateBean(dynAttrMap);
        clazz = dynamicBean.getClass();
    }

    public DynmicVO(Object object) throws IllegalAccessException, NoSuchFieldException { 
   
        dynamicBean = generateBean(getFields(object));
        Map<String, Object> values = getValues(object);
        Iterator<String> iterator = values.keySet().iterator();
        while (iterator.hasNext()) { 
   
            String key = iterator.next();
            Object value = values.get(key);
            put(key, value);
        }
        clazz = dynamicBean.getClass();
    }

    public static DynmicVO parseMap(Map<String, Object> targetMap) throws NoSuchFieldException, IllegalAccessException { 
   
        DynmicVO dynmicVO = new DynmicVO();
        for (Map.Entry<String, Object> entry : targetMap.entrySet()) { 
   
            dynmicVO.put(entry.getKey(), entry.getValue());
        }
        return dynmicVO;
    }

    public static DynmicVO parseString(String jsonString) throws NoSuchFieldException, IllegalAccessException { 
   
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        return parseMap(jsonObject);
    }

    /**
     * 获取所有属性值
     *
     * @return
     * @throws IllegalAccessException
     */
    public Map<String, Object> getValues() throws IllegalAccessException { 
   
        Map<String, Object> fieldValuesMap = new HashMap<>(16);
        if (clazz != null) { 
   
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) { 
   
                field.setAccessible(true);
                Object fieldValue = field.get(dynamicBean);
                fieldValuesMap.put(field.getName().split("\\$cglib_prop_")[1], fieldValue);
            }
            return fieldValuesMap;
        }
        return fieldValuesMap;
    }

    /**
     * 获取所有属性值
     *
     * @return
     * @throws IllegalAccessException
     */
    public Map<String, Object> getValues(Object object) throws IllegalAccessException { 
   
        Map<String, Object> fieldValuesMap = new HashMap<>(16);
        Class<?> clazz = object.getClass();
        if (clazz != null) { 
   
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) { 
   
                field.setAccessible(true);
                Object fieldValue = field.get(object);
                fieldValuesMap.put(field.getName(), fieldValue);
            }
            return fieldValuesMap;
        }
        return fieldValuesMap;
    }

    /**
     * 设置属性值,不存在就添加
     *
     * @param property
     * @param value
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public void put(String property, Object value) throws IllegalAccessException, NoSuchFieldException { 
   
        Field declaredField;
        try { 
   
            declaredField = clazz.getDeclaredField("$cglib_prop_" + property);
        } catch (Exception e) { 
   
            Map<String, Class<?>> fields = getFields();
            fields.put(property, Object.class);

            Map<String, Object> values = getValues();

            this.dynamicBean = generateBean(fields);
            this.clazz = dynamicBean.getClass();

            values.put(property, value);
            Iterator<String> iterator = values.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String putKey = iterator.next();
                Object putValue = values.get(putKey);
                Field field = clazz.getDeclaredField("$cglib_prop_" + putKey);
                field.setAccessible(true);
                field.set(dynamicBean, putValue);
            }
            return;
        }
        declaredField.setAccessible(true);
        declaredField.set(dynamicBean, value);
    }

    /**
     * 在已有的实体上添加属性
     *
     * @param object
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public void putAll(Object object) throws IllegalAccessException, NoSuchFieldException { 
   
        Class<?> clazz = object.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        Map<String, Object> fieldValuesMap = new HashMap<>(16);
        Map<String, Object> fieldTypeMap = new HashMap<>(16);
        for (Field field : declaredFields) { 
   
            field.setAccessible(true);
            Object fieldValue = field.get(object);
            fieldValuesMap.put(field.getName(), fieldValue);
            fieldTypeMap.put(field.getName(), field.getType());
        }
        //获取当前的属性及属性值
        fieldTypeMap.putAll(getFields());
        fieldValuesMap.putAll(getValues());
        this.dynamicBean = generateBean(fieldTypeMap);
        this.clazz = dynamicBean.getClass();
        Iterator<String> iterator = fieldValuesMap.keySet().iterator();
        while (iterator.hasNext()) { 
   
            String key = iterator.next();
            Object value = fieldValuesMap.get(key);
            put(key, value);
        }
    }

    public Map<String, Class<?>> getFields() throws IllegalAccessException { 
   
        Map<String, Class<?>> attrMap = new HashMap<>(16);
        if (clazz != null) { 
   
            Iterator<String> iterator = getValues().keySet().iterator();

            while (iterator.hasNext()) { 
   
                attrMap.put(iterator.next(), Object.class);
            }
        }
        return attrMap;
    }

    /**
     * 获取对象所有属性及对应的类别
     *
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public Map<String, Class<?>> getFields(Object object) throws IllegalAccessException { 
   
        Class<?> clazz = object.getClass();
        Map<String, Class<?>> attrMap = new HashMap<>(16);
        if (clazz != null) { 
   
            Iterator<String> iterator = getValues(object).keySet().iterator();

            while (iterator.hasNext()) { 
   
                attrMap.put(iterator.next(), Object.class);
            }
        }
        return attrMap;
    }

    /**
     * 获取属性值
     *
     * @param property 设置的字段
     * @return JsonNode对象
     */
    public JsonNode get(String property) { 
   
        JsonNode jsonNode = objectMapper.valueToTree(dynamicBean);
        return jsonNode.get(property);
    }

    /**
     * 获取属性值
     *
     * @param property 设置的字段
     * @return 属性对应的对象
     * @throws NoSuchFieldException   没有字段
     * @throws IllegalAccessException 反射错误
     */
    @SuppressWarnings("unchecked")
    public <E extends Object> E getToObject(String property) throws NoSuchFieldException, IllegalAccessException { 
   
        Field declaredField = clazz.getDeclaredField("$cglib_prop_" + property);
        declaredField.setAccessible(true);
        Class<?> type = declaredField.getType();
        return (E) declaredField.get(dynamicBean);
    }


    public Object getEntity() { 
   
        return this.dynamicBean;
    }

    private Object generateBean(Map dynAttrMap) { 
   
        BeanGenerator generator = new BeanGenerator();
        if (dynAttrMap != null) { 
   
            Iterator iterator = dynAttrMap.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String key = iterator.next().toString();
                generator.addProperty(key, (Class) dynAttrMap.get(key));
            }
        }
        return generator.create();
    }
}

test.class测试类测试动态生成bean

package com.dym.attr;

import com.dym.entity.DynamicBeanEntity;
import org.apache.commons.collections.map.MultiValueMap;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: zhaoxu
 * @description:
 */
public class test { 
   
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { 
   
        // 设置属性们,默认16
        HashMap propertyMap = new HashMap(16);

        propertyMap.put("name", String.class);

        propertyMap.put("age", Integer.class);

        propertyMap.put("height", Double.class);

        // 生成动态 Entity
        DynamicBeanEntity bean = new DynamicBeanEntity(propertyMap);

        //设置属性值
        bean.setValue("name", "zx");
        bean.setValue("age", 22);
        bean.setValue("height", 175.0);

        //获取属性值
        Map<String, Object> values = bean.getValues();

        //获取可执行的方法
        MultiValueMap methods = bean.getMethods();

        //执行某个方法
        bean.executeMethod("setAge", 23);

        System.out.println("动态bean的age属性:"+bean.getValue("age"));
 DynmicVO dynmicVO = new DynmicVO(pipeVo);
                    //返回直接添加物料的属性
//                    dynmicVO.setValue(materialEntity,MaterialEntity.class);

                    //返回添加mediumVo的属性
                    dynmicVO.setValue("mediumVo", baseConverter.convertSingleObject(materialEntity, MaterialVO.class));
    }
}

test.class测试类测试链接数据库动态生成bean

package com.dym.test;

import com.dym.util.DBUtil;
import com.dym.util.DynmicEntity;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: zhaoxu
 * @description:
 */
@Component
public class test { 
   
    public static void main(String[] args) { 
   
        ArrayList<DynmicEntity> beans = new ArrayList<>();
        Connection conn = null;
        PreparedStatement prst = null;
        String sql = "";
        sql = "select table_name from information_schema.tables where table_schema=\'public\'";
        conn = DBUtil.getConn();
        try { 
   
            prst = conn.prepareStatement(sql);
            ResultSet rs = prst.executeQuery();
            while (rs.next()) { 
   
                String tableName = rs.getString(1);
                Map attrMap = new HashMap<>();
                String findFieldSql = "SELECT format_type(a.atttypid,a.atttypmod) as type,a.attname as name, a.attnotnull as notnull \n" +
                        "FROM pg_class as c,pg_attribute as a where c.relname = \'" + tableName + "\' and a.attrelid = c.oid and a.attnum>0";
                PreparedStatement fieldsPrst = conn.prepareStatement(findFieldSql);
                ResultSet fieldsRs = fieldsPrst.executeQuery();
                while (fieldsRs.next()) { 
   
                    String fieldType = fieldsRs.getString(1);
                    String fieldName = fieldsRs.getString(2);
                    attrMap.put(fieldName, Object.class);
                }
                DynmicEntity bean = new DynmicEntity(attrMap);
                beans.add(bean);
            }
        } catch (SQLException e) { 
   
            e.printStackTrace();
        }

        DBUtil.close(prst, conn);
    }
}

DBUtil.class:

package com.dym.util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author: zhaoxu
 * @description:
 */
public class DBUtil { 
   
    private final static String URL="jdbc:postgresql://localhost:5432/dynmic";
    private final static String NAME="postgres";
    private final static String PASS="123456";
    private static Connection conn=null;

    /**
     *
     *@Title:DBUtil
     *@Description:
     */
    public DBUtil(){ 
   

    }

    /**
     *
     * @Tiltle getConn
     * @return Connection
     * @Description:返回连接
     */
    public static Connection getConn(){ 
   
        //告诉jvm使用mysql
        try { 
   
            //加载驱动,string为驱动名字
            Class.forName("org.postgresql.Driver");
            //连接数据库,得到Connection连接
            conn=DriverManager.getConnection(URL,NAME,PASS);
            //System.out.println("连接数据库: "+conn);
        }catch(ClassNotFoundException e) { 
   
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch(SQLException e){ 
   
            e.printStackTrace();
        }
        return conn;
    }

    //关闭结果对象集
    public static void close(ResultSet rs){ 
   
        if(rs!=null){ 
   
            try{ 
   
                rs.close();
            }catch(SQLException e){ 
   
                e.printStackTrace();
            }
        }
    }

    //关闭编译语句对象
    public static void close(PreparedStatement prst){ 
   
        if(prst!=null){ 
   
            try{ 
   
                prst.close();
            }catch(SQLException e){ 
   
                e.printStackTrace();
            }
        }
    }

    //关闭结果对象集
    public static void close(Connection conn){ 
   
        if(conn!=null){ 
   
            try{ 
   
                conn.close();
            }catch(SQLException e){ 
   
                e.printStackTrace();
            }
        }
    }

    //对于更新操作关闭资源
    public static void close(PreparedStatement prst,Connection conn){ 
   
        close(prst);
        close(conn);
    }

    //关闭所有
    public static void close(ResultSet rs,PreparedStatement prst,Connection conn){ 
   
        close(rs);
        close(prst);
        close(conn);
    }
}

github地址:

https://github.com/zhao458114067/repository-util
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/130975.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 深入理解C++11_c++ string char

    深入理解C++11_c++ string char1.语法decltype(expression)decltype(declaretype)用于查询表达式的类型,即编译时期进行自动类型推导。如上所示,该语句返回expression表达式的类型。注意:decltype仅仅是查询表达式的类型,并不会对表达式求值。2.推导规则1)如果expression是一个不被括号()包围的表达式,或者是一个类成员访问表达式,或者是一个单独的变量,那么decltype(exp)的类型就和exp一致,这是最普遍最常见的情况。2)

  • 面试官问我:一个 TCP 连接可以发多少个 HTTP 请求?我竟然回答不上来..

    面试官问我:一个 TCP 连接可以发多少个 HTTP 请求?我竟然回答不上来..

  • postman最新版_postcrossing中文版

    postman最新版_postcrossing中文版PostmanCn最新版本:7.36.1更新时间:2020-12-18点击下载https://www.postman.com/downloads/这个是Postman官网的下载页面https://gitee.com/hlmd/PostmanCn/attach_files/492931/download/postman_EnToCn.zip这个是这里的汉化的介绍Postman中文版汉化持续更新中安装教程WindowsPostman-*-win64-中文版…

  • git 查看远程所有分支_git同步分支

    git 查看远程所有分支_git同步分支gitremote-v

  • struts2拦截器详解_拦截和修改tcp数据

    struts2拦截器详解_拦截和修改tcp数据Struts2中的拦截器和servelt中的过滤器是非常的相似的。如果学过过滤器的话,肯定能够感觉的到,尽管有些微的不同。可是struts2的拦截器到底如何使用呢,为什么会有这些配置呢?接下来一一来看。 过滤器和拦截器是非常相似的,过滤器publicinterfaceFilter接口里面有三个方法: init(FilterConfigfilterConfig),des

  • Java学习之Maven使用

    Java学习之Maven0x00前言学习并mark过来一些知识点做留存。0x01Maven使用compiled(默认)对主程序是否有效:有效对测试程序是否有效:有效是否参与打包:参

    2021年12月13日

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号