Building Schneider Building Control system Database Backend Server example Project Five (Java Dynamic generation Class)

Source: Internet
Author: User
Tags generator object object

In the process of making the database easy tool, we encountered the problem that after the program deployment started running under Tomcat, we could not define the hibernate bean object of the table structure subsequently created in the database, so we need to create the Bean object dynamically after the server is running. Cglib This open source repository solves our problem and dynamically creates Java objects.
Introduction to 1.cglib Open Source Library
CGLIB (Code Generation Library) is an open source project that is a powerful, high-performance, high-quality Code generation class library that can extend Java classes and implement Java interfaces at run time.
The post-compilation Cglib structure is as follows:

which
? Net.sf.cglib.core
The underlying bytecode processing classes, most of them related to ASM.
? Net.sf.cglib.transform
Conversions for compile-time or run-time classes and class files
? Net.sf.cglib.proxy
Implementing classes that create proxies and method interceptors
? Net.sf.cglib.reflect
Classes that implement fast reflection and C # style proxies
? Net.sf.cglib.util
Collection Sort Tool Class
? Net.sf.cglib.beans
JavaBean Related Tool Classes
2. In the dynamically generated class object, Cglib uses the following code:
1) Dynamically generated class object operation class

 PackageSzx.core.util.sub;ImportJava.util.Iterator;ImportJava.util.Map;ImportJava.util.Set;ImportNet.sf.cglib.beans.BeanGenerator;ImportNet.sf.cglib.beans.BeanMap; Public  class dynamicbean {    PrivateObject object =NULL;//Dynamically generated classes    PrivateBeanmap Beanmap =NULL;//Store property names and types of properties     Public Dynamicbean() {Super(); }@SuppressWarnings("Rawtypes") Public Dynamicbean(Map PropertyMap) { This. Object = Generatebean (PropertyMap); This. Beanmap = Beanmap.create ( This. Object); }/** * Assign value to bean attribute * @param Property name * @param Value * * *     Public void SetValue(object property, Object value)    {Beanmap.put (property, value); }/** * Property value is obtained by property name * @param Property attribute name * @return Value * *     PublicObjectGetValue(String property) {returnBeanmap.get (property); }/** * Gets the entity Bean Object * @return  */     PublicObjectGetObject() {return  This. Object; }/** * @param propertymap * @return * *    @SuppressWarnings("Rawtypes")PrivateObjectGeneratebean(Map PropertyMap) {Beangenerator Generator =NewBeangenerator (); Set KeySet = Propertymap.keyset (); for(Iterator i = Keyset.iterator (); I.hasnext ();)            {String key = (string) i.next ();        Generator.addproperty (Key, (Class) Propertymap.get (key)); }returnGenerator.create (); }}

2) Generate Dynamicbean class

Public list<object> executesqlgetcolumandvalue (String sql) {map<string, class> columnmap = new Hash Map<string, Class> ();Dynamicbean beanutil = null;Object OB = NULL;Connection conn = null;ResultSet rs = null;ResultSetMetaData RSM = null;list<object> list = null;try {conn = Sessionfactoryutils. Getdatasource(Super. Getsessionfactory()). getconnection();RSM = conn. Preparestatement(SQL). ExecuteQuery(). GetMetaData();for (int i =1; I <= rsm.getcolumncount (); i++){Columnmap. Put(RSM. getColumnName(i), Class. forname(RSM. Getcolumnclassname(i)));System. out. println("ColName:"+rsm. getColumnName(i). toString()//                      +", Colnamevalue"+rsm. Getcolumnclassname(i). toString());} OB = new Dynamicbean (COLUMNMAP). GetObject();RS = conn. Preparestatement(SQL). ExecuteQuery();List = new Linkedlist<object> ();ClassCLS= OB. GetClass();field[] Fields =CLS. Getdeclaredfields();while (RS. Next()) {Object TMP =CLS. newinstance();for (int i =0; i < fields.length; i++){String fieldName = fields[i]. GetName(). Replace("$cglib _prop_","");String Setmethodname ="Set"+ FieldName. Substring(0,1). toUpperCase() + FieldName. Substring(1);Method Setmethod =CLS. Getdeclaredmethod(Setmethodname, New Class[]{fields[i]. GetType()});Setmethod. Invoke(TMP, RS. GetObject(FieldName));System. out. println("FieldName:"+fieldname+", Setmethodname:"+setmethodname+", \nsetmethod:"+setmethod);} list. Add(TMP);} return List;} catch (Exception ex) {throw new RuntimeException (ex);} finally {try {} catch (Exception ex) {} try {conn. Close();} catch (Exception ex) {}}}

The example function above is to read the table data from the database and assign the read value to the dynamically created object.
The core code for using Cglib is as follows:

map<string, class> columnmap = new hashmap<string, class> ();Dynamicbean beanutil = null;Object OB = NULL;..... columnmap. Put(RSM. getColumnName(i), Class. forname(RSM. Getcolumnclassname(i)));... ob = new Dynamicbean (COLUMNMAP). GetObject();ClassCLS= OB. GetClass();field[] Fields =CLS. Getdeclaredfields();while (RS. Next()) {Object TMP =CLS. newinstance();for (int i =0; i < fields.length; i++){String fieldName = fields[i]. GetName(). Replace("$cglib _prop_","");String Setmethodname ="Set"+ FieldName. Substring(0,1). toUpperCase() + FieldName. Substring(1);Method Setmethod =CLS. Getdeclaredmethod(Setmethodname, New Class[]{fields[i]. GetType()});Setmethod. Invoke(TMP, RS. GetObject(FieldName));} list. Add(TMP);}

3) Read attributes and property values from a newly generated Dynamicbean object

Jsonobject jsonobject = new Jsonobject ();Class Valueclz = value. GetClass();System. out. println("VALUECLZ:"+VALUECLZ);if (VALUECLZ. toString(). Contains("Beangeneratorbycglib") {Field fields[] = value. GetClass(). Getdeclaredfields();//Get all Properties of an objectfor (int j =0; J < Fields.length; J + +) {Field field = Fields[j];Field. Setaccessible(true);//Modify access rightsString propertyname = Fields[j]. GetName(). Replace("$cglib _prop_","");;Jsonobject. Put(PropertyName, Object2jsonobject (field. Get(value)));System. out. println(PropertyName +":"+ Field. Get(value));}}

The above determines whether the class name contains the string "Beangeneratorbycglib", only the tool class used to generate the JSON string Jsonutil to judge that the current object is the object Cglib created.
The above gets the properties and values of the object using the reflection mechanism of java.
Class output generated by 3.CGLIB

Dynamically generated class name: class Net.sf.Cglib.Empty.object$$BeanGeneratorByCGLIB$$5FB90C30 Property Name:$cglib _prop_alarmtypetext, Value: Normal property name:$cglib _prop_rownumberValue:1Property name:$cglib _prop_alarmtypeidValue:0....................................Generated JSON string: {"ACK": {"Items":[{"Alarmtypetext":"NORMAL","RowNumber":1,"Alarmtypeid":0}], "Totalnum": 1}}

4. Other
1) in Hibernate or Mapping, Spring AOP is used by Cglib to complete its function.
2) Cglib processing dynamically generated classes, you can also complete the dynamic proxy, that is, the agent does not implement the interface of the inherited class, you can use the Cglib package. Since the JDK started with the 1.3 release, it introduced dynamic proxies and was often used to dynamically create proxies. The dynamic proxy for the JDK is very simple to use, but it has a limitation that objects that use dynamic proxies must implement one or more interfaces. If you want to broker an inherited class that does not implement an interface, you need to use the Cglib package.
3) The Cglib is implemented by ASM, ASM is a Java bytecode manipulation framework that delves into the principles of the Java Virtual machine JVM that needs to be immediately first.
The above three points need to study one by one, this article is not detailed introduction.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Building Schneider Building Control system Database Backend Server example Project Five (Java Dynamic generation Class)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.