Code Implementation
Package me. andy. practice. annotation; import Java. lang. reflect. constructor; import Java. lang. reflect. field; import Java. lang. reflect. method; public class reflectutils {public static object copy (Object Resource) throws exception {class <? Extends Object> classtype = resource. getclass (); object newobject = classtype. newinstance (); field [] declaredfields = classtype. getdeclaredfields (); For (field filed: declaredfields) {string firstletter = filed. getname (). substring (0, 1 ). touppercase (); string getmethodname = "get" + firstletter + filed. getname (). substring (1); string setmethodname = "set" + firstletter + filed. getname (). substring (1); Method getmethod = classtype. getmethod (getmethodname, new class [] {}); Method setmethod = classtype. getmethod (setmethodname, new class [] {filed. getType ()}); object value = getmethod. invoke (resource, new object [] {}); setmethod. invoke (newobject, new object [] {value}) ;}return newobject ;}}
Object newobject = classtype. newinstance ();
Equivalent
Constructor <? Extends Object> constructor = classtype. getconstructor (new class [] {});
Object newobject = constructor. newinstance (new object [] {});
Field [] declaredfields = classtype. getdeclaredfields () returns all methods declared by the current class (including private)
Classtype. getfields () returns the total methods of the current class, including
Test code
Package me. andy. practice. reflect; import me. andy. practice. annotation. reflectutils; import Org. JUnit. test; import Java. lang. reflect. constructor; import Java. lang. reflect. field; import Java. lang. reflect. method; import static JUnit. framework. assert. assertequals; public class reflecttest {@ test public void test_copy () throws exception {person = new person ("Andy", 1); person copyperson = (person) reflectutils. copy (person); assertequals ("Andy", copyperson. getname (); assertequals (integer. valueof (1), copyperson. getage ());}}
Package me. andy. practice. reflect; public class person {private string name; private integer age; Public Person () {} public person (string name, integer age) {This. name = Name; this. age = age;} Public String getname () {return name;} public void setname (string name) {This. name = Name;} public integer getage () {return age;} public void setage (integer age) {This. age = age ;}}