您好,登錄后才能下訂單哦!
如何在java中利用cglib動態生成一個實體bean?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
<dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.3</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>3.2.4</version> </dependency>
package com.dym.entity; import net.sf.cglib.beans.BeanGenerator; import org.apache.commons.collections.map.MultiValueMap; import java.lang.reflect.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * @author: zhaoxu * @description: */ public class DynamicBeanEntity { Object dynamicBean; Class clazz; public DynamicBeanEntity(Map dynAttrMap) { this.dynamicBean = generateBean(dynAttrMap); clazz = dynamicBean.getClass(); } /** * 獲取所有屬性值 * * @return * @throws IllegalAccessException */ public Map<String, Object> getValues() throws IllegalAccessException { Map<String, Object> fieldValuesMap = new HashMap(16); 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; } /** * 獲取動態bean所有方法信息 * * @return */ public MultiValueMap getMethods() { MultiValueMap map = new MultiValueMap(); Method[] methods = clazz.getMethods(); for (Method method : methods) { Type[] genericParameterTypes = method.getGenericParameterTypes(); if (genericParameterTypes.length > 0) { for (Type type : genericParameterTypes) { map.put(method.getName(), type); } } else { map.put(method.getName(), null); } } return map; } /** * 執行某個方法 * * @param methodName * @param parameters * @return * @throws InvocationTargetException * @throws IllegalAccessException * @throws NoSuchMethodException */ public Object executeMethod(String methodName, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { ArrayList<Class> paramTypeList = new ArrayList(); for (Object paramType : parameters) { paramTypeList.add(paramType.getClass()); } Class[] classArray = new Class[paramTypeList.size()]; Method method = clazz.getMethod(methodName, paramTypeList.toArray(classArray)); Object invoke = method.invoke(dynamicBean, parameters); return invoke; } /** * 設置屬性值 * * @param property * @param value * @throws NoSuchFieldException * @throws IllegalAccessException */ public void setValue(String property, Object value) throws NoSuchFieldException, IllegalAccessException { Field declaredField = clazz.getDeclaredField("$cglib_prop_" + property); declaredField.setAccessible(true); declaredField.set(dynamicBean, value); } /** * 獲取屬性值 * * @param property * @return * @throws NoSuchFieldException * @throws IllegalAccessException */ public Object getValue(String property) throws NoSuchFieldException, IllegalAccessException { Field declaredField = clazz.getDeclaredField("$cglib_prop_" + property); declaredField.setAccessible(true); Object value = declaredField.get(dynamicBean); return value; } public Object getEntity() { return this.dynamicBean; } /** * 利用cglib的BeanGenerator創建對象 * * @param dynAttrMap * @return */ private Object generateBean(Map dynAttrMap) { BeanGenerator generator = new BeanGenerator(); Iterator iterator = dynAttrMap.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next().toString(); generator.addProperty(key, (Class) dynAttrMap.get(key)); } return generator.create(); } }
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")); } }
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); } }
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); } }
補充:java 反射 json動態轉實體類
我就廢話不多說了,大家還是直接看代碼吧~
package test.refect; public class Student { // 姓名 private String name; // 年齡 private String age; // 住址 private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", address=" + address + "]"; } public void sayHello(Book book){ System.out.println(book.getName()); } }
package test.refect; public class Book { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
package test.refect; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URLDecoder; import java.util.Iterator; import net.sf.json.JSONObject; public class Main { public static void main(String[] args) throws Exception { //Student str --> Student 主類 String str = "test.refect.Student"; Class<?> clazz = Class.forName(str); //Book實體 str --> Book 參數類 String bookStr = "test.refect.Book"; Class<?> bookClazz = Class.forName(bookStr); //json --> Book 將參數類轉為JSONOBJECT String bookJson ="{\"name\":\"Java\"}"; JSONObject jsonObject=JSONObject.fromObject(bookJson); //實例化參數類 Object bookInStance = bookClazz.newInstance(); // 通過JSONOBJECT 為參數類賦值 Iterator<?> keys = jsonObject.keys(); while (keys.hasNext()) { Object key = keys.next(); Object value = jsonObject.get(key); // 替換非法字符 String _key = String.valueOf(key).replaceFirst("\\W", ""); Field field = bookClazz.getDeclaredField(_key); field.setAccessible(true); field.set(bookInStance, URLDecoder.decode(String.valueOf(value), "UTF-8")); field.setAccessible(false); } //將參數類注入到主類 Method method = clazz.getDeclaredMethod("sayHello", bookClazz); //執行主類 method.invoke(clazz.newInstance(), bookInStance); } }
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。