好多自己需要的功能,别人都写好了,多学习,加以复用。
构建自己的代码库。
1、通过注解@NotNull,提示 调用方,参数不能为空
2、org.apache.commons.lang3.Validate.notNull
比自己再写,封装的好啊。
public static <T extends Model<T>> Integer count(@NotNull String sql, @Nullable Object... paras) {
if(StringUtils.isEmpty(sql)){
throw new JtnException("The sql cannot be empty");
}
}
public static <T extends Model<T>> boolean deleteByIdList(@NotEmpty List<?> idList,@NotNull Class<T> modelClass) {
Validate.notNull(modelClass, "The modelClass can't be null");
Validate.notEmpty(idList, "The idList cannot be empty");
boolean existFailed = false;
for (Object id : idList) {
boolean succeed = deleteById(id, modelClass);
existFailed &= succeed;
}
return existFailed;
}
3、com.vip.vjtools.vjkit.reflect.ReflectionUtil
反射工具。
JFinal的model没有 属性,只有get和set方法。
直接调用getFieldValue("id") 会报异常
getPropertyValue,通过getter方法。
/**
* 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
*
* 性能较差, 用于单次调用的场景
*/
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
Field field = getField(obj.getClass(), fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + ']');
}
setField(obj, field, value);
}
/**
* 使用预先获取的Field, 直接读取对象属性值, 不经过setter函数.
*
* 用于反复调用的场景.
*/
public static void setField(final Object obj, Field field, final Object value) {
try {
field.set(obj, value);
} catch (Exception e) {
throw convertReflectionExceptionToUnchecked(e);
}
}
/**
* 先尝试用Getter函数读取, 如果不存在则直接读取变量.
*
* 性能较差, 用于单次调用的场景
*/
public static <T> T getProperty(Object obj, String propertyName) {
Method method = getGetterMethod(obj.getClass(), propertyName);
if (method != null) {
return invokeMethod(obj, method);
} else {
return getFieldValue(obj, propertyName);
}
}
/**
* 先尝试用Setter函数写入, 如果不存在则直接写入变量, 按传入value的类型匹配函数.
*
* 性能较差, 用于单次调用的场景
*/
public static void setProperty(Object obj, String propertyName, final Object value) {
Method method = getSetterMethod(obj.getClass(), propertyName, value.getClass());
if (method != null) {
invokeMethod(obj, method, value);
} else {
setFieldValue(obj, propertyName, value);
}
}