//通过反射机制实现 某个字段加一 减一操作,
//现实程序中会有好多时候需要对数据库的某字段加一 ,比如访问量,下载量等,如果每次都是 读取数据对象然后修改相应变量 然后在保存数据对象,这种操作的话
//每次碰到一个不同的字段名称就需要写一次这样的函数
//本代码只要传入 要修改的对象 传入域名 返回一个修改好的对象 直接保存
package edu.socialmedia.aas.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class FieldAddOneUtil{
/**
* @author younker
* @desc 实现对数据中某个整型域加一操作
* @param object 要被修改的数据
* @param fieldName 要加一的域名称 首字母要大写
*/
public static Object addOne(Object object,String fieldName){
fieldName=fieldName.substring(0, 1).toUpperCase()+fieldName.replaceFirst("\\w","");//首字母大写
Class<?> c = object.getClass();
try {
Method setMethod = c.getMethod("set"+fieldName, Integer.class);
Method getMethod = c.getMethod("get"+fieldName);
Integer i = null;
try {
i = (Integer)getMethod.invoke(object);
i = i+1;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
try {
setMethod.invoke(object, i);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return object;
}
public static Object subOne(Object object,String fieldName){
fieldName=fieldName.substring(0, 1).toUpperCase()+fieldName.replaceFirst("\\w","");//首字母大写
Class<?> c = object.getClass();
try {
Method setMethod = c.getMethod("set"+fieldName, Integer.class);
Method getMethod = c.getMethod("get"+fieldName);
Integer i = null;
try {
i = (Integer)getMethod.invoke(object);
i = i-1;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
try {
setMethod.invoke(object, i);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return object;
}
}