大家好,又见面了,我是你们的朋友全栈君。
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账号...