问题描述
packageshengsiyuan.reflection;importjava.lang.reflect.Field;importjava.lang.reflect.Method;publicclassReflectTester{publicObjectcopy(Objectobject)throwsException{Class<?>classType=object.getClass();ObjectobjectCopy=classType.getConstructor(newClass[]{}).newInstance(newObject[]{});Field[]fields=classType.getDeclaredFields();for(Fieldfield:fields){Stringname=field.getName();StringfirstLetter=name.substring(0,1).toUpperCase();StringgetMethodName="get"+firstLetter+name.substring(1);StringsetMethodName="set"+firstLetter+name.substring(1);MethodgetMethod=classType.getMethod(getMethodName,newClass[]{});MethodsetMethod=classType.getMethod(setMethodName,newClass[]{field.getType()});Objectvalue=getMethod.invoke(object,newObject[]{});setMethod.invoke(objectCopy,newObject[]{value});}/*Constructorcons=classType.getConstructor(newClass[]{String.class,int.class});Objectobj2=classType.newInstance();Objectobj=cons.newInstance(newObject[]{"hello",3});System.out.println(obj);*/returnobjectCopy;}publicstaticvoidmain(String[]args)throwsException{Customercustomer=newCustomer("Tom",20);customer.setId(1L);ReflectTestertest=newReflectTester();Customercustomer2=(Customer)test.copy(customer);System.out.println(customer2.getId()+","+customer2.getAge()+","+customer2.getName());}}classCustomer{privateLongid;privateStringname;privateintage;Customer(){}Customer(Stringname,intage){this.name=name;this.age=age;}publicLonggetId(){returnid;}publicvoidsetId(Longid){this.id=id;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicintgetAge(){returnage;}publicvoidsetAge(intage){this.age=age;}}为什么运行总出现下面情况:Exceptioninthread"main"java.lang.NoSuchMethodException:shengsiyuan.reflection.Customer.<init>()atjava.lang.Class.getConstructor0(Class.java:2706)atjava.lang.Class.getConstructor(Class.java:1657)atshengsiyuan.reflection.ReflectTester.copy(ReflectTester.java:11)atshengsiyuan.reflection.ReflectTester.main(ReflectTester.java:51)