Original Java uses reflection and custom annotations to achieve a comparison of object differences

Source: Internet
Author: User

There is a logic in Java Project C, where the resource data (type Resourceitem, with the int/double/boolean/string type of dozens of fields) needs to be different from each change in the resource data and describes the change. Not all fields need to be compared, such as ID fields do not participate in the alignment. It would be a heavy-duty job, in turn, to write code for each field. High-level languages give us a lot of convenience and should be used. First define your own annotations, value values are used as field descriptions
@Target (Elementtype.field) @Retention (retentionpolicy.runtime)  public @Interface  revisioncolumn {    String value ();}
Add the note for all Resourceitem fields, such as
 Public classResourceitem {Private intID; Private intrevision; Privateresourceitemstatus status; @RevisionColumn (Node)    PrivateString node; @RevisionColumn ("Physical Isolation")    Private Booleanphysicalisolation; @RevisionColumn ("Whole machine: single-disk maximum (%)")    Private intMachinedisklimit; //...}
Describes the entity type that first defines the difference in the Record object field before the comparison to logic
 Public classFieldchangeinfoImplementsserializable{PrivateString PropertyName; PrivateString Propertyheader; PrivateObject from; PrivateObject to;  PublicFieldchangeinfo () {} PublicFieldchangeinfo (String propertyname, String Propertyheader, object from, object to) { This. PropertyName =PropertyName;  This. Propertyheader =Propertyheader;  This. from =From ;  This. to =to ; } @Override Public Booleanequals (Object obj) {if(! (objinstanceoffieldchangeinfo)) return false; if(obj = = This)            return true; Fieldchangeinfo RHS=(fieldchangeinfo) obj; return NewEqualsbuilder ().                Append (PropertyName, Rhs.propertyname).                Append (Propertyheader, Rhs.propertyheader).                Append (from, Rhs.from).                Append (To, rhs.to).    Isequals (); }      PublicString Getpropertyname () {returnPropertyName; }      Public voidSetpropertyname (String PropertyName) { This. PropertyName =PropertyName; }      PublicString Getpropertyheader () {returnPropertyheader; }      Public voidSetpropertyheader (String propertyheader) { This. Propertyheader =Propertyheader; }      PublicObject Getfrom () {returnFrom ; }      Public voidSetfrom (Object from) { This. from =From ; }      PublicObject Getto () {returnto ; }      Public voidSetto (Object to) { This. to =to ; }}
FieldchangeinfoResource data Alignment logic, implement the following tool method 1, parameters accept Resourceitem old and new two objects 2, through reflection, Class.getdeclaredfields get the type of all fields 3, Call the Getannotation method of the field instance to get the Revisioncolumn annotation object, if it is not null, the field sets the annotation, makes a comparison of 4, gets the field value, detects a null reference, calls the Equals method to do a value match, and a mismatch occurs. Create Filedchangeinfo object record difference Information 5, return the Difference information collection
     Public StaticList<fieldchangeinfo>Getresourceitemfieldchangeinfo (Resourceitem originalitem, Resourceitem updateditem) {Try{List<FieldChangeInfo> Fieldchangeinfos =NewLinkedlist<>();  for(Field Field:resourceitem.class. Getdeclaredfields ()) {Revisioncolumn Revisioncolumn= Field.getannotation (revisioncolumn.class); if(Revisioncolumn! =NULL) {field.setaccessible (true); Object OriginalValue=Field.get (Originalitem); Object Updatedvalue=Field.get (Updateditem); if(OriginalValue = =NULL&& Updatedvalue = =NULL)                        Continue; if(OriginalValue = =NULL|| !originalvalue.equals (Updatedvalue)) {Fieldchangeinfo Fieldchangeinfo=NewFieldchangeinfo ();                        Fieldchangeinfo.setfrom (OriginalValue);                        Fieldchangeinfo.setto (Updatedvalue);                        Fieldchangeinfo.setpropertyname (Field.getname ());                        Fieldchangeinfo.setpropertyheader (Revisioncolumn.value ());                    Fieldchangeinfos.add (Fieldchangeinfo); }                }            }            returnFieldchangeinfos; } Catch(illegalaccessexception e) {Throw NewRuntimeException ("An exception occurred while detecting Resourceitem field changes"); }    }
GetresourceitemfieldchangeinfoIf necessary, you can convert a little refactoring to a generic method that supports the differential detection of which data types

Original Java uses reflection and custom annotations to achieve a comparison of object differences

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.