Public static object copy (Object OBJ) throws exception {class <?> Classtype = obj. getclass (); // construct an object copyoj = classtype with no parameters. getconstructor (new class [] {}). newinstance (new object [] {}); // obtains the attribute array field [] fields = classtype of the source object. getdeclaredfields (); // retrieve the array and assign a value for (field F: fields) {string fieldname = f. getname (); string fristchar = fieldname. substring (0, 1 ). touppercase (); string setmethodname = "set" + fristchar + fieldname. substring (1); string getmethodname = "get" + fristchar + fieldname. substring (1); Method setmethod = classtype. getdeclaredmethod (setmethodname, new class [] {f. getType ()}); Method getmethod = classtype. getdeclaredmethod (getmethodname, new class [] {}); object result = getmethod. invoke (OBJ); setmethod. invoke (copyoj, new object [] {result});} return copyoj ;}
copy an object Using Reflection