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

时间:2022-06-01 02:00:15
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Timestamp;

class Person {
private String name;
private int age;

private Timestamp birth;

public Timestamp getBirth() {
return birth;
}

public void setBirth(Timestamp birth) {
this.birth = birth;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public void setAge(int age) {
this.age = age;
}

public int getAge() {
return this.age;
}
}

/*****************************************************/
public class InvokeSetterMethod {
public static void main(String[] args) {
Person p
= new Person();
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方法
*
*
@param obj
*
@param att
*
@param value
*
@param type
*/
public static void invokeSetterMethodByType(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 = new PropertyDescriptor(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方法
*
*
@param obj
*
@param att
*
@param value
*
@param type
*/
public static void setter(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方法
*
*
@param obj
*
@param att
*/
public static void getter(Object obj, String att) {
try {
Method met
= obj.getClass().getMethod("get" + initStr(att));
System.out.println(met.invoke(obj));
}
catch (Exception e) {
e.printStackTrace();
}
}

/**
* 将单词的首字母大写
*
*
@param old
*
@return
*/
public static String initStr(String old) {
String str
= old.substring(0, 1).toUpperCase() + old.substring(1);
return str;
}
}