Java Reflection Tool Class--gets/sets the object property value by specifying the property name

Source: Internet
Author: User

Java objects do not use loops such as for,while to manipulate object properties through the dot operator, which is the main solution to this problem.

For example, there is an object containing a property that has a certain regularity

Obj1: {    name1: "Zhang San",    age1:1,    name2: "John Doe",    age2:2,    ....}

  

To split this object into multiple small objects

objlist:[{         name: "Zhang San",         age:1}, {         name: "John Doe",         Age:2}]

To cope with this inability to use loops to get properties, this tool class was written

The core implementation code is as follows:

/** * @param o * Operation Object * @param methodName * Method Name * @param attname * Property name * @param value * The value * @return The Get method returns the actual value of the Set method after the return operation of the object */private static objects operation (object o, String methodName, String Attnam E, class<?> paramtype, Object value) {//Method Assignment Error Flag Boolean operr = False;object res = null; class<?> type = O.getclass (); try {method = Null;if (Methodname.indexof ("get")! =-1) {//Get method//Get method        method = Type.getmethod (MethodName); Execute res = Method.invoke (o);}        else {//Set method//Get parameter type by value when no incoming parameter type Paramtype = Paramtype = = null? Value.getclass (): Paramtype;        Get Methods method = Type.getmethod (MethodName, Paramtype); Execute Method.invoke (o, value); res = o;}} catch (Exception e) {//Get/set method Operation Property Failed Operr = True;if (show_log) {System.err.println (Getthisname () + ": [WARN] Direct operate on the attribute ' + AttName + ' (without the help of the Get/set method). ");}}        if (operr) {//The value is manipulated directly by breaking the package try {field field = NULL; Get property Field = Type.getdeclaredfield (AttName); Break Package field.setaccessible (TRUE); if (Methodname.indexof ("get")! =-1) {//Get method//Get property value res = Field.get (o); } else {//Set method//Sets property value Field.set (o, value); res = o;}} catch (Exception e) {///two methods both failed if (Show_log) {System.err.println (Getthisname () + ": [ERROR] Property '" + AttName + "' operation failed."); }}return Res;}

  

The Set method is as follows:

/** * Set Property value *  * @param o *            Action Object * @param attname *            Property name * @param value *            parameter value * @param paramtype *            parameter type * @return After Operation object */@SuppressWarnings ("unchecked") public static <T> T set (t o, String attname, object value, class< ?> paramtype) {if (o = = NULL | | attname = = NULL | | attname.isempty ()) {return null;} String methodName = Attnamehandle ("set", AttName), return (T) operation (O, MethodName, AttName, Paramtype, value);}

The Get method is as follows:

/** * Get Property value *  * @param o *            operand * @param attname *            Property name * @param returntype *            return value type * @return */@SuppressWa Rnings ("unchecked") public static <T> T get (Object o, String attname, class<t> returntype) {if (o = = NULL | | at Tname = = NULL | | Attname.isempty ()) {return null;} String methodName = Attnamehandle ("Get", AttName), return (T) operation (O, methodName, attname, NULL, NULL);}

Get the Get/set method name by property name:

    /** *     Property name Processing     *     * @param     Method *            Methods (get/set)     * @param attname     * @return    * * private static string Attnamehandle (String method, String attname) {        StringBuffer res = new StringBuffer (method);//Genus Sex has only one letter        if (attname.length () = = 1) {            res.append (attname.touppercase ());        } else {//attribute contains two letters and above            char[] Chararray = Attname.tochararray (); When the current two characters are lowercase, convert the first letter to uppercase            if (Character.islowercase (chararray[0]) && character.islowercase (chararray[1] ) {                res.append (character.touppercase (chararray[0)));                Res.append (attname.substring (1));            } else {                res.append (attname);            }        }         return res.tostring ();    }

  

Complete code: Https://github.com/GFuZan/reflexTools

Java Reflection Tool Class--gets/sets the object property value by specifying the property name

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.