At the time of development, it may be possible to copy the property value of a class to another class, which may be encountered frequently when reading and writing the database, especially for a class with an inheritance relationship, we need to rewrite a lot of redundant code, there is an easy way to implement this function,
1, first there are two classes, two classes have the same property name and type, there are different property names are very type:
publicclass ClassTestCopy2 { privateint id; private String name; private String password; private String sex; private String age; //get和set方法}
publicclass ClassTestCopy1 { privateint id; private String name; private String password; //get和set方法}
2, the following is the realization of the function of the method body:
public static void Copy (object source, Object dest) throws Exception {//Get property BeanInfo Sourcebean = Introsp Ector. Getbeaninfo(Source. GetClass(), Java. Lang. Object. Class);propertydescriptor[] Sourceproperty = Sourcebean. Getpropertydescriptors();BeanInfo Destbean = Introspector. Getbeaninfo(dest. GetClass(), Java. Lang. Object. Class);propertydescriptor[] Destproperty = Destbean. Getpropertydescriptors();try {for (int i =0; i < sourceproperty.length; i++) {for (int j =0; J < Destproperty.length; J + +) {if (Sourceproperty[i]. GetName(). Equals(Destproperty[j]. GetName())) {//Invoke Source's Getter method and Dest setter method Destproperty[j]. Getwritemethod(). Invoke(Dest, Sourceproperty[i]. Getreadmethod(). Invoke(source)); Break;}}}} catch (Exception e) {throw new Exception ("Property replication failed:"+ E. GetMessage());} }
3. Test below:
public static void Main (string[] args) {ClassTestCopy1 C1 = new ClassTestCopy1 (1205030213,"Name:xuliugen","password:123456");ClassTestCopy2 C2 = new ClassTestCopy2 ();try {copybeanparamstest. Copy(c1, C2);System. out. println("-------------C1----------------");System. out. println(C2. GetId());System. out. println(C2. GetName());System. out. println(C2. GetPassword());System. out. println(C2. Getsex());System. out. println(C2. Getage());} catch (Exception e) {E. Printstacktrace();} }
4. The test results are as follows:
It is known that attributes with the same property name and type are assigned, and the remainder is null if the result is not matched;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java implements the mutual assignment of properties between different classes