Public classReflecttester { PublicObject copy (Object object)throwsException {//get the type of objectClass<?> ClassType =Object.getclass (); System.out.println ("Class:" +classtype.getname ()); //creates a new object with the default constructor, and new class[] {} does not have a parameter representing the default construction methodObject objectcopy = Classtype.getconstructor (Newclass[] {}). newinstance (Newobject[] {}); //gets all the properties of the object, including the privateField fields[] =Classtype.getdeclaredfields (); for(inti = 0; i < fields.length; i++) {Field field=Fields[i]; String FieldName=Field.getname (); String Firstletter= fieldname.substring (0, 1). toUpperCase (); //get the name of the GetXXX () method corresponding to the attributeString getmethodname = "Get" + Firstletter + fieldname.substring (1); //get the name of the Setxxx () method corresponding to the attributeString setmethodname = "Set" + Firstletter + fieldname.substring (1); //The GetXXX () method corresponding to the property is obtained, and the corresponding method is obtained according to the name and parameter, and GetXXX () is not a parameter, so the emptyMethod GetMethod =Classtype.getmethod (Getmethodname,Newclass[] {}); //get the Setxxx () method corresponding to the attribute, setxxx (Object obj), setxxx is a parameter, so the type of the current field is passedMethod Setmethod =Classtype.getmethod (Setmethodname,Newclass[] {field.gettype ()}); //Call the GetXXX () method of the original object, call GetXXX () to get the value of the original objectObject value = Getmethod.invoke (object,Newobject[] {}); System.out.println (FieldName+ ":" +value); //call the Copy object's Setxxx () method, and call the new object's Setxxx () to set the value inSetmethod.invoke (Objectcopy,Newobject[] {value}); } returnobjectcopy;} Public Static voidMain (string[] args)throwsException {Customer Customer=NewCustomer ("Shmilyzl", 25); Customer.setid (NewLong (1)); Customer customercopy= (Customer)Newreflecttester (). copy (customer); System.out.println ("Copy Information:" + customercopy.getid () + "" + customercopy.getname () + "" +customercopy.getage ()); }} Packagecom.fahon.mytest;classCustomer {PrivateLong ID;PrivateString name;Private intAge ; PublicCustomer () {} PublicCustomer (String name,intAge ) { This. Name =name; This. Age =Age ;} PublicLong getId () {returnID;} Public voidsetId (Long id) { This. ID =ID;} PublicString GetName () {returnname;} Public voidsetName (String name) { This. Name =name;} Public intGetage () {returnAge ;} Public voidSetage (intAge ) { This. Age =Age ;}}Class:com.fahon.mytest.Customerid:1Name:shmilyzlage:25Copy Information:1 Shmilyzl 25
Reflection Dark Horse Programmer