java timestamp 默认值_java 反射: 当Timestamp类型的属性值为null时,设置默认值

本文介绍了一种使用Java反射API调用特定类型的Setter方法的方法,并通过示例展示了如何为一个`Person`类的对象设置`Timestamp`类型的属性。此外,还提供了一个处理属性值为空时设置默认值的解决方案。

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 void setAge(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());

}/*** 调用setter方法

*

*@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) {//属性类型

String type =field.getType().getName();//属性名

String name =field.getName();//属性值

PropertyDescriptor pd = newPropertyDescriptor(field.getName(),

cl);

Method getMethod=pd.getReadMethod();

Object o=getMethod.invoke(obj);//当Timestamp类型的属性值为null时,设置默认值

if (methodType.equals(type) && null ==o) {

setter(obj, name, param, paramType);

}

}

}catch(Exception e) {

e.printStackTrace();

}

}/*** 调用setter方法

*

*@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();

}

}/*** 调用getter方法

*

*@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();

}

}/*** 将单词的首字母大写

*

*@paramold

*@return

*/

public staticString initStr(String old) {

String str= old.substring(0, 1).toUpperCase() + old.substring(1);returnstr;

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值