ImportJava.beans.PropertyDescriptor;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;ImportJava.sql.Timestamp;classPerson {PrivateString name; Private intAge ; PrivateTimestamp Birth; PublicTimestamp Getbirth () {returnbirth; } Public voidSetbirth (Timestamp birth) { This. Birth =birth; } PublicString GetName () {return This. Name; } Public voidsetName (String name) { This. Name =name; } Public voidSetage (intAge ) { This. Age =Age ; } Public intGetage () {return This. Age; }}/*****************************************************/ Public classInvokesettermethod { Public Static voidMain (string[] args) {person P=NewPerson (); Invokesettermethodbytype (P, person.class, "Java.sql.Timestamp", Timestamp.valueof ("1111-11-11 11:11:11"), Timestamp.class); P.setbirth (Timestamp.valueof ("2014-12-11 00:00:00")); System.out.println (P.getbirth ()); } /*** Call Setter method * *@paramobj *@paramatt *@paramValue *@paramtype*/ Public Static voidinvokesettermethodbytype (Object obj, class cl, String methodtype, Timestamp param, class<?>Paramtype) { Try{field[] f=Cl.getdeclaredfields (); for(Field field:f) {//Property TypeString type =Field.gettype (). GetName (); //Property nameString name =Field.getname (); //Property ValuePropertyDescriptor PD =NewPropertyDescriptor (Field.getname (), CL); Method GetMethod=Pd.getreadmethod (); Object o=Getmethod.invoke (obj); //When the property value of the timestamp type is NULL, the default value is set if(Methodtype.equals (type) &&NULL==o) {setter (obj, name, param, paramtype); } } } Catch(Exception e) {e.printstacktrace (); } } /*** Call Setter method * *@paramobj *@paramatt *@paramValue *@paramtype*/ Public Static voidSetter (Object obj, String att, object value, Class<?>type) { Try{Method met= Obj.getclass (). GetMethod ("set" +initstr (ATT), type); Met.invoke (obj, value); } Catch(Exception e) {e.printstacktrace (); } } /*** Call getter Method * *@paramobj *@paramatt*/ Public Static voidGetter (Object obj, String att) {Try{Method met= Obj.getclass (). GetMethod ("get" +initstr (ATT)); System.out.println (Met.invoke (obj)); } Catch(Exception e) {e.printstacktrace (); } } /*** Capitalize the first letter of the word * *@paramOld *@return */ Public Staticstring Initstr (String old) {string str= old.substring (0, 1). toUpperCase () + old.substring (1); returnstr; }}
Java Reflection: Sets the default value when the property value of the timestamp type is null