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

被折叠的 条评论
为什么被折叠?



