Copy partial attributes between two classes in Java

Source: Internet
Author: User

Beanutils. copyproperties (to, from); all attributes copy is similar to overwrite

Private Static void copyproperties (Object O1, object O2 ){

String filename, STR, getname, setname;
List fields = new arraylist ();
Method getmethod = NULL;
Method setmethod = NULL;
Try {
Class C1 = o1.getclass ();
Class C2 = o2.getclass ();

Field [] fs1 = c1.getdeclaredfields ();
Field [] fs2 = c2.getdeclaredfields ();
// Two class attributes are excluded from the comparison and only the same attributes are left.
For (INT I = 0; I <fs2.length; I ++ ){
For (Int J = 0; j <fs1.length; j ++ ){
If (fs1 [J]. getname (). Equals (fs2 [I]. getname ())){
Fields. Add (fs1 [J]);
Break;
}
}
}
If (null! = Fields & fields. Size ()> 0 ){
For (INT I = 0; I <fields. Size (); I ++ ){
// Get the property name
Field F = (field) fields. Get (I );
Filename = f. getname ();
// The first letter of the attribute name is capitalized.
STR = filename. substring (0, 1). touppercase ();
// Concatenate the getxxx and setxxx method names
Getname = "get" + STR + filename. substring (1 );
Setname = "set" + STR + filename. substring (1 );
// Get and set methods
Getmethod = c1.getmethod (getname, new class [] {});
Setmethod = c2.getmethod (setname, new class [] {f. GetType ()});

// Obtain the property value
Object o = getmethod. Invoke (O1, new object [] {});
System. Out. println (filename + ":" + O );
// Put the property value into the corresponding property of another object
If (null! = O ){

System. Out. println ("o2.setmethod =" + setmethod );

Setmethod. Invoke (O2, new object [] {o });
}
}
}
} Catch (securityexception e ){
E. printstacktrace ();
} Catch (nosuchmethodexception e ){
E. printstacktrace ();
} Catch (illegalargumentexception e ){
E. printstacktrace ();
} Catch (illegalaccessexception e ){
E. printstacktrace ();
} Catch (invocationtargetexception e ){
E. printstacktrace ();
}
}

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.