之前经常遇到一类问题,就是需要为一个pojo类设置属性值,但是有时反复调用会比较麻烦,就可以利用java的反射机制。
pojo类:
public class DotStat implements Serializable {
private Integer id;
private String model;
private String adccompany;
private String ossdk;
private String av;
private String phone;
private Integer enterpriseId;
private String cityPinyin;
private Integer industryId;
private Date statDate;
--------------------------------------------
get and set method
}
//利用反射的方法,我们需要给DotStat类的id属性赋值,参数是属性名,需要赋的值,该DotStat对象
private void setAttributeValue2DotStat(String attributeName, Integer times, DotStat dot) {
//将属性名的第一个字母大写。
String setAttributeMethodName = "set"+ Character.toUpperCase(attributeName.charAt(0)) + attributeName.substring(1);
try {
Method setAttributeMethod = DotStat.class.getDeclaredMethod(setAttributeMethodName,Integer.class);
setAttributeMethod.invoke(dot,st.getTimes());
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
这就是利用反射机制为属性赋值