JAVA "Dynamic" adds properties to a class

Source: Internet
Author: User

Section reference: http://www.cnblogs.com/zy2009/p/6725843.html

Added in Pom.xml:

<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>

  

To dynamically generate class code using Cglib:

Package Com.frinder.util;import Net.sf.cglib.beans.beangenerator;import Net.sf.cglib.beans.beanmap;import java.util.map;/** * Created by Frinder on 2017/7/18.    */public class Dynamicbean {/** * target object */private object target;    /** * Attribute Collection */private Beanmap beanmap; Public Dynamicbean () {} public Dynamicbean (map<string, class> propertymap) {this.target = Generatebea        N (propertymap);    This.beanmap = Beanmap.create (this.target); The/** * Bean adds attributes and values * @param property * @param value */public void SetValue (String properties,    Object value) {Beanmap.put (property, value);        }/** * Gets the property value * * @param properties * @return */public Object GetValue (String) {    Return Beanmap.get (property);    }/** * Gets the object * * @return */public Object Gettarget () {return target;  /** * Generate object based on attribute * * @param propertymap * @return * *  Private Object Generatebean (map<string, class> propertymap) {beangenerator generator = new Beangenerator ()        ;        Propertymap.foreach (k, v), Generator.addproperty (k, v));    return Generator.create (); }}

  

Use Commons-beanutils to get the source object properties-type collection, encapsulate the new object, and set the value code:

Package Com.frinder.util;import Com.kiktech.entity.loggerentity;import Net.logstash.logback.encoder.org.apache.commons.lang.builder.reflectiontostringbuilder;import Org.apache.commons.beanutils.propertyutilsbean;import Org.slf4j.logger;import Org.slf4j.LoggerFactory;import Java.beans.propertydescriptor;import java.util.hashmap;import java.util.map;/** * Created by Frinder on 2017/7/18.    */public class Reflectutil {static Logger Logger = Loggerfactory.getlogger (Reflectutil.class);        public static Dynamicbean Gettarget (Object target, map<string, object> addproperties) {//Get property Map        Propertyutilsbean Propertyutilsbean = new Propertyutilsbean ();        propertydescriptor[] descriptors = propertyutilsbean.getpropertydescriptors (target);        map<string, class> propertymap = new HashMap (); for (PropertyDescriptor d:descriptors) {if (!) Class ". Equalsignorecase (D.getname ())) {Propertymap.put (D.getname (), D.getpropertytYpe ());        }}//Add extra Properties Addproperties.foreach ((k, V), Propertymap.put (K, V.getclass ()));        New Dynamic bean Dynamicbean Dynamicbean = new Dynamicbean (PROPERTYMAP); Add old value Propertymap.foreach (K, v)-{try {dynamicbean.setvalue (k, Propert            Yutilsbean.getnestedproperty (target, k));            } catch (Exception e) {logger.error (E.getmessage (), E);        }        });        Add extra Value Addproperties.foreach (k, v), Dynamicbean.setvalue (k, v));    return Dynamicbean;        } public static void Main (string[] args) {loggerentity entity = new loggerentity ();        Entity.setappname ("appname");        Entity.setoperator ("add");        Entity.setresult ("result");        Entity.seturi ("uri");        Entity.setmethod ("method");   map<string, object> addproperties = new HashMap () {{put ("Hello", "World");         Put ("abc", "123");        }};    System.out.println (Reflectiontostringbuilder.tostring (Gettarget (Entity, addproperties)); }}

  

Loggerentity Code:

Package Com.frinder.entity;import net.logstash.logback.encoder.org.apache.commons.lang.builder.reflectiontostringbuilder;/** * Created by Frinder on 2017/5/24.    */public class Loggerentity {private String method;    Private String URI;    Private object[] args;    Private Object result;    Private String operator;    Private String AppName;    /** * Get Current Object * * @param method * @param uri * @param args * @param result * @return * *        Public loggerentity Get (string method, String uri, object[] args, Object result, string operator, string appName) {        Setmethod (method);        Seturi (URI);        Setargs (args);        Setresult (result);        Setoperator (operator);        Setappname (AppName);    return this;    } public String GetMethod () {return method;    } public void Setmethod (String method) {This.method = method;    } public String GetURI () {return URI; } public void Seturi (String uri) {This.uri = URI;    } public object[] Getargs () {return args;    } public void Setargs (object[] args) {This.args = args;    } public Object GetResult () {return result;    } public void Setresult (Object result) {This.result = result;    } public String Getoperator () {return operator;    } public void Setoperator (String operator) {this.operator = operator;    } public String Getappname () {return appName;    } public void Setappname (String appName) {this.appname = AppName;    } @Override Public String toString () {return reflectiontostringbuilder.tostring (this); }}

  

Test results:

JAVA "Dynamic" adds properties to a class

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.