cn.hutool.core.util.ReflectUtil Java Examples

The following examples show how to use cn.hutool.core.util.ReflectUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HtmlMakerFactory.java    From bitchat with Apache License 2.0 6 votes vote down vote up
/**
 * 创建HtmlMaker实例
 */
public HtmlMaker build(HtmlMakerEnum type, Class<? extends HtmlMaker> clazz) {
    if (type == null) {
        return null;
    } else {
        HtmlMaker htmlMaker = htmlMakerMap.get(type);
        if (htmlMaker == null) {
            lock.lock();
            try {
                if (!htmlMakerMap.containsKey(type)) {
                    htmlMaker = ReflectUtil.newInstance(clazz);
                    htmlMakerMap.putIfAbsent(type, htmlMaker);
                } else {
                    htmlMaker = htmlMakerMap.get(type);
                }
            } finally {
                lock.unlock();
            }
        }
        return htmlMaker;
    }
}
 
Example #2
Source File: MessageController.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 判断Bean是否为空对象或者空白字符串,空对象表示本身为<code>null</code>或者所有属性都为<code>null</code>
 *
 * @param bean Bean对象
 * @return 是否为空,<code>true</code> - 空 / <code>false</code> - 非空
 */
private boolean isBlank(Object bean) {
    if (null != bean) {
        for (Field field : ReflectUtil.getFields(bean.getClass())) {
            Object fieldValue = ReflectUtil.getFieldValue(bean, field);
            if (null != fieldValue) {
                if (fieldValue instanceof String && StrUtil.isNotBlank((String) fieldValue)) {
                    return false;
                } else if (!(fieldValue instanceof String)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #3
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 获取字段列表 {@code 过滤数据库中不存在的字段,以及自增列}
 *
 * @param t          对象
 * @param ignoreNull 是否忽略空值
 * @return 字段列表
 */
private List<Field> getField(T t, Boolean ignoreNull) {
	// 获取所有字段,包含父类中的字段
	Field[] fields = ReflectUtil.getFields(t.getClass());

	// 过滤数据库中不存在的字段,以及自增列
	List<Field> filterField;
	Stream<Field> fieldStream = CollUtil.toList(fields).stream().filter(field -> ObjectUtil.isNull(field.getAnnotation(Ignore.class)) || ObjectUtil.isNull(field.getAnnotation(Pk.class)));

	// 是否过滤字段值为null的字段
	if (ignoreNull) {
		filterField = fieldStream.filter(field -> ObjectUtil.isNotNull(ReflectUtil.getFieldValue(t, field))).collect(Collectors.toList());
	} else {
		filterField = fieldStream.collect(Collectors.toList());
	}
	return filterField;
}
 
Example #4
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 根据对象查询
 *
 * @param t 查询条件
 * @return 对象列表
 */
public List<T> findByExample(T t) {
	String tableName = getTableName(t);
	List<Field> filterField = getField(t, true);
	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());

	String where = StrUtil.join(" ", columns);
	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
	List<T> ret = CollUtil.newArrayList();
	maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
	return ret;
}
 
Example #5
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用根据主键更新,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param pk         主键
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer updateById(T t, P pk, Boolean ignoreNull) {
	String tableName = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> StrUtil.appendIfMissing(s, " = ?")).collect(Collectors.toList());
	String params = StrUtil.join(Const.SEPARATOR_COMMA, columns);

	// 构造值
	List<Object> valueList = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).collect(Collectors.toList());
	valueList.add(pk);

	Object[] values = ArrayUtil.toArray(valueList, Object.class);

	String sql = StrUtil.format("UPDATE {table} SET {params} where id = ?", Dict.create().set("table", tableName).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #6
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用插入,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer insert(T t, Boolean ignoreNull) {
	String table = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	String columns = StrUtil.join(Const.SEPARATOR_COMMA, columnList);

	// 构造占位符
	String params = StrUtil.repeatAndJoin("?", columnList.size(), Const.SEPARATOR_COMMA);

	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("INSERT INTO {table} ({columns}) VALUES ({params})", Dict.create().set("table", table).set("columns", columns).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #7
Source File: ExcelUtil.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 获取bean中的属性值
 *
 * @param vo         实体对象
 * @param field      字段
 * @param excelField 注解
 * @return 最终的属性值
 * @throws Exception
 */
private Object getTargetValue(T vo, Field field, ExcelField excelField) throws Exception {
	Object o = ReflectUtil.getFieldValue(vo, field);
	if (ObjectUtil.isEmpty(o)) {
		o = ClassUtil.invokeGetter(vo, field.getName());
	}
	if (StringUtil.isNotEmpty(excelField.targetAttr())) {
		String target = excelField.targetAttr();
		if (target.indexOf(StringUtil.DOT) > -1) {
			String[] targets = target.split("[.]");
			for (String name : targets) {
				o = getValue(o, name);
			}
		} else {
			o = getValue(o, target);
		}
	}
	return o;
}
 
Example #8
Source File: HtmlMakerFactory.java    From redant with Apache License 2.0 6 votes vote down vote up
/**
 * 创建HtmlMaker实例
 */
public HtmlMaker build(HtmlMakerEnum type,Class<? extends HtmlMaker> clazz){
    if(type==null){
        return null;
    }else{
        HtmlMaker htmlMaker = htmlMakerMap.get(type);
        if(htmlMaker==null){
            lock.lock();
            try {
                if(!htmlMakerMap.containsKey(type)) {
                    htmlMaker = ReflectUtil.newInstance(clazz);
                    htmlMakerMap.putIfAbsent(type,htmlMaker);
                }else{
                    htmlMaker = htmlMakerMap.get(type);
                }
            }finally {
                lock.unlock();
            }
        }
        return htmlMaker;
    }
}
 
Example #9
Source File: MessageController.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 判断Bean是否为空对象或者空白字符串,空对象表示本身为<code>null</code>或者所有属性都为<code>null</code>
 *
 * @param bean Bean对象
 * @return 是否为空,<code>true</code> - 空 / <code>false</code> - 非空
 */
private boolean isBlank(Object bean) {
    if (null != bean) {
        for (Field field : ReflectUtil.getFields(bean.getClass())) {
            Object fieldValue = ReflectUtil.getFieldValue(bean, field);
            if (null != fieldValue) {
                if (fieldValue instanceof String && StrUtil.isNotBlank((String) fieldValue)) {
                    return false;
                } else if (!(fieldValue instanceof String)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #10
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 获取字段列表 {@code 过滤数据库中不存在的字段,以及自增列}
 *
 * @param t          对象
 * @param ignoreNull 是否忽略空值
 * @return 字段列表
 */
private List<Field> getField(T t, Boolean ignoreNull) {
	// 获取所有字段,包含父类中的字段
	Field[] fields = ReflectUtil.getFields(t.getClass());

	// 过滤数据库中不存在的字段,以及自增列
	List<Field> filterField;
	Stream<Field> fieldStream = CollUtil.toList(fields).stream().filter(field -> ObjectUtil.isNull(field.getAnnotation(Ignore.class)) || ObjectUtil.isNull(field.getAnnotation(Pk.class)));

	// 是否过滤字段值为null的字段
	if (ignoreNull) {
		filterField = fieldStream.filter(field -> ObjectUtil.isNotNull(ReflectUtil.getFieldValue(t, field))).collect(Collectors.toList());
	} else {
		filterField = fieldStream.collect(Collectors.toList());
	}
	return filterField;
}
 
Example #11
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 根据对象查询
 *
 * @param t 查询条件
 * @return 对象列表
 */
public List<T> findByExample(T t) {
	String tableName = getTableName(t);
	List<Field> filterField = getField(t, true);
	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());

	String where = StrUtil.join(" ", columns);
	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
	List<T> ret = CollUtil.newArrayList();
	maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
	return ret;
}
 
Example #12
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用根据主键更新,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param pk         主键
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer updateById(T t, P pk, Boolean ignoreNull) {
	String tableName = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> StrUtil.appendIfMissing(s, " = ?")).collect(Collectors.toList());
	String params = StrUtil.join(Const.SEPARATOR_COMMA, columns);

	// 构造值
	List<Object> valueList = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).collect(Collectors.toList());
	valueList.add(pk);

	Object[] values = ArrayUtil.toArray(valueList, Object.class);

	String sql = StrUtil.format("UPDATE {table} SET {params} where id = ?", Dict.create().set("table", tableName).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #13
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用插入,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer insert(T t, Boolean ignoreNull) {
	String table = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	String columns = StrUtil.join(Const.SEPARATOR_COMMA, columnList);

	// 构造占位符
	String params = StrUtil.repeatAndJoin("?", columnList.size(), Const.SEPARATOR_COMMA);

	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("INSERT INTO {table} ({columns}) VALUES ({params})", Dict.create().set("table", table).set("columns", columns).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #14
Source File: NoBootTest.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    TestModel obj = new TestModel();
    obj.setStation(new RemoteData<>(101L));
    obj.setOrg2(new RemoteData<>(101L));

    Field[] fields = ReflectUtil.getFields(obj.getClass());
    for (Field field : fields) {
        InjectionField anno = field.getDeclaredAnnotation(InjectionField.class);
        if (anno == null) {
            continue;
        }
        field.setAccessible(true);

        String api = anno.api();
        Class<?> feign = anno.feign();

        if (StrUtil.isEmpty(api) && Object.class.equals(feign)) {
            log.warn("忽略注入字段: {}.{}", field.getType(), field.getName());
            continue;
        }


    }
}
 
Example #15
Source File: I18nTransformUtil.java    From scaffold-cloud with MIT License 6 votes vote down vote up
/**
 * @param object    需要被转换的对象 需要有i18nNid属性 存储标识
 * @param fieldName 需要被转换的字段名
 * @param <T>       泛型
 * @return 原对象转换后
 */
public static <T> T transForm(T object, String fieldName) {
    Object i18nId = ReflectUtil.getFieldValue(object, "i18nNid");
    MessageSource messageSource = SpringContextHolder.getBean("messageSource");
    if (Objects.nonNull(i18nId)) {
        String name = null;
        try {
            name = messageSource.getMessage(i18nId.toString(), null, LocaleContextHolder.getLocale());
            if (StrUtil.isNotBlank(name)) {
                if(name.equals(i18nId)){
                    log.warn("i18n:{}对应的国际化配置在数据库不存在,请检查!", i18nId);
                }else{
                    ReflectUtil.setFieldValue(object, fieldName, name);
                }
            }else{
                log.warn("获取的国际化属性{}不合法,i18nNid:{},语言:{}", fieldName, i18nId, LocaleContextHolder.getLocale());
            }
        } catch (NoSuchMessageException e) {
            log.error("NoSuchMessageException=> 国际化属性{}不合法,i18nNid:{},语言:{}", fieldName, i18nId, LocaleContextHolder.getLocale());
        }
    } else {
        log.warn("存在不合法的i18nId");
    }
    return object;
}
 
Example #16
Source File: MessageController.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 判断Bean是否为空对象或者空白字符串,空对象表示本身为<code>null</code>或者所有属性都为<code>null</code>
 *
 * @param bean Bean对象
 * @return 是否为空,<code>true</code> - 空 / <code>false</code> - 非空
 */
private boolean isBlank(Object bean) {
    if (null != bean) {
        for (Field field : ReflectUtil.getFields(bean.getClass())) {
            Object fieldValue = ReflectUtil.getFieldValue(bean, field);
            if (null != fieldValue) {
                if (fieldValue instanceof String && StrUtil.isNotBlank((String) fieldValue)) {
                    return false;
                } else if (!(fieldValue instanceof String)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #17
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 根据对象查询
 *
 * @param t 查询条件
 * @return 对象列表
 */
public List<T> findByExample(T t) {
	String tableName = getTableName(t);
	List<Field> filterField = getField(t, true);
	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());

	String where = StrUtil.join(" ", columns);
	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
	List<T> ret = CollUtil.newArrayList();
	maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
	return ret;
}
 
Example #18
Source File: IocHelper.java    From openAGV with Apache License 2.0 6 votes vote down vote up
private static Object getDbInjectDao(Field field, Class<?> paramTypeClass) {
        String key = paramTypeClass.getName();
        Object dbDaoObj = DB_DAO_MAP.get(key);
        if (ToolsKit.isEmpty(dbDaoObj)) {
            String dbClientId = "";
            if (null != field) {
                DbClient dbClient = field.getAnnotation(DbClient.class);
                dbClientId = ToolsKit.isNotEmpty(dbClient) ? dbClient.id() : "";
                if (ToolsKit.isEmpty(dbClientId)) {
                    Import importAnn = field.getAnnotation(Import.class);
                    dbClientId = importAnn.client();
                }
            }
//            List<?> proxyList = null;
//            dbDaoObj =  MongoUtils.getMongoDao(dbClientId, paramTypeClass, proxyList);
            dbDaoObj = ReflectUtil.newInstance(MongoDao.class, dbClientId, paramTypeClass);
            DB_DAO_MAP.put(key, dbDaoObj);
        }
        return DB_DAO_MAP.get(key);
    }
 
Example #19
Source File: RouteHelper.java    From openAGV with Apache License 2.0 6 votes vote down vote up
private void routeAction() {
    if (isRestart()) {
        return;
    }
    if (ACTION_ROUTE_MAP.isEmpty()) {
        List<Class<?>> actionClassList = ClassHelper.duang().getActionClassList();
        if (ToolsKit.isEmpty(actionClassList)) {
            LOG.info("工站逻辑处理类为空,退出routeAction方法");
            return;
        }
        for (Class<?> actionClass : actionClassList) {
            Action actionAonn = actionClass.getAnnotation(Action.class);
            if (ToolsKit.isEmpty(actionAonn)) {
                continue;
            }
            IAction action = (IAction) ReflectUtil.newInstance(actionClass);
            if (ToolsKit.isNotEmpty(action)) {
                String key = action.actionKey();
                Route route = new Route(key, action);
                ACTION_ROUTE_MAP.put(key, route);
                BeanHelper.duang().setBean(route.getServiceObj());
            }
        }
        printActionKey();
    }
}
 
Example #20
Source File: RouteHelper.java    From openAGV with Apache License 2.0 6 votes vote down vote up
private void routeListener() {
    if (LISTENER_ROUTE_MAP.isEmpty()) {
        List<Class<?>> listenerClassList = ClassHelper.duang().getListenerClassList();
        if (ToolsKit.isEmpty(listenerClassList)) {
            LOG.info("监听器类为空,退出routeListener方法");
            return;
        }
        for (Class<?> listenerClass : listenerClassList) {
            Listener listenerAnnot = listenerClass.getAnnotation(Listener.class);
            if (ToolsKit.isEmpty(listenerAnnot)) {
                continue;
            }
            EventListener eventListener = (EventListener) ReflectUtil.newInstance(listenerClass);
            if (ToolsKit.isNotEmpty(eventListener)) {
                String key = listenerAnnot.key();
                if (ToolsKit.isEmpty(key)) {
                    key = listenerClass.getName();
                }
                Route route = new Route(key, eventListener);
                LISTENER_ROUTE_MAP.put(key, route);
                BeanHelper.duang().setBean(route.getServiceObj());
            }
        }
        printListenetKey();
    }
}
 
Example #21
Source File: ActionRequest.java    From openAGV with Apache License 2.0 6 votes vote down vote up
public static String callServiceMethod(ServiceRequestDto serviceRequestDto) {
    Object service = BeanHelper.duang().getBean(serviceRequestDto.getServiceClass());
    if (ToolsKit.isEmpty(service)) {
        throw new RobotException("根据["+serviceRequestDto.getServiceClass().getName()+"]没有找到实例对象,请检查!");
    }
    try {
        Object resultObj = ReflectUtil.invoke(service, serviceRequestDto.getMethodName(), serviceRequestDto.getParam());
        String result = "";
        if (resultObj instanceof String) {
            result = resultObj.toString();
        } else if (resultObj instanceof IProtocol) {
            result = ((IProtocol) resultObj).getParams();
        }
        return result;
    } catch (Exception e) {
        throw new RobotException(e.getMessage(), e);
    }
}
 
Example #22
Source File: BeanPropertyRowMapper.java    From yue-library with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the mapping meta-data for the given class.
 * @param mappedClass the mapped class
 */
protected void initialize(Class<T> mappedClass) {
	this.mappedClass = mappedClass;
	this.mappedFields = new HashMap<>();
	this.mappedProperties = new HashSet<>();
	PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
	for (PropertyDescriptor pd : pds) {
		if (pd.getWriteMethod() != null) {
			String databaseFieldName = AnnotationUtil.getAnnotationValue(ReflectUtil.getField(mappedClass, pd.getName()), FieldName.class);
			if (StrUtil.isNotEmpty(databaseFieldName)) {
				this.mappedFields.put(databaseFieldName, pd);
			} else {
				this.mappedFields.put(lowerCaseName(pd.getName()), pd);
				String underscoredName = underscoreName(pd.getName());
				if (!lowerCaseName(pd.getName()).equals(underscoredName)) {
					this.mappedFields.put(underscoredName, pd);
				}
			}
			
			this.mappedProperties.add(pd.getName());
		}
	}
}
 
Example #23
Source File: NoBootTest.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    TestModel obj = new TestModel();
    obj.setStation(new RemoteData<>(101L));
    obj.setOrg2(new RemoteData<>(101L));

    Field[] fields = ReflectUtil.getFields(obj.getClass());
    for (Field field : fields) {
        InjectionField anno = field.getDeclaredAnnotation(InjectionField.class);
        if (anno == null) {
            continue;
        }
        field.setAccessible(true);

        String api = anno.api();
        Class<?> feign = anno.feign();

        if (StrUtil.isEmpty(api) && Object.class.equals(feign)) {
            log.warn("忽略注入字段: {}.{}", field.getType(), field.getName());
            continue;
        }


    }
}
 
Example #24
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 获取字段列表 {@code 过滤数据库中不存在的字段,以及自增列}
 *
 * @param t          对象
 * @param ignoreNull 是否忽略空值
 * @return 字段列表
 */
private List<Field> getField(T t, Boolean ignoreNull) {
	// 获取所有字段,包含父类中的字段
	Field[] fields = ReflectUtil.getFields(t.getClass());

	// 过滤数据库中不存在的字段,以及自增列
	List<Field> filterField;
	Stream<Field> fieldStream = CollUtil.toList(fields).stream().filter(field -> ObjectUtil.isNull(field.getAnnotation(Ignore.class)) || ObjectUtil.isNull(field.getAnnotation(Pk.class)));

	// 是否过滤字段值为null的字段
	if (ignoreNull) {
		filterField = fieldStream.filter(field -> ObjectUtil.isNotNull(ReflectUtil.getFieldValue(t, field))).collect(Collectors.toList());
	} else {
		filterField = fieldStream.collect(Collectors.toList());
	}
	return filterField;
}
 
Example #25
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用根据主键更新,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param pk         主键
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer updateById(T t, P pk, Boolean ignoreNull) {
	String tableName = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> StrUtil.appendIfMissing(s, " = ?")).collect(Collectors.toList());
	String params = StrUtil.join(Const.SEPARATOR_COMMA, columns);

	// 构造值
	List<Object> valueList = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).collect(Collectors.toList());
	valueList.add(pk);

	Object[] values = ArrayUtil.toArray(valueList, Object.class);

	String sql = StrUtil.format("UPDATE {table} SET {params} where id = ?", Dict.create().set("table", tableName).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #26
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用插入,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer insert(T t, Boolean ignoreNull) {
	String table = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	String columns = StrUtil.join(Const.SEPARATOR_COMMA, columnList);

	// 构造占位符
	String params = StrUtil.repeatAndJoin("?", columnList.size(), Const.SEPARATOR_COMMA);

	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("INSERT INTO {table} ({columns}) VALUES ({params})", Dict.create().set("table", table).set("columns", columns).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #27
Source File: ClassUtil.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 调用Setter方法, 仅匹配方法名。 支持多级,如:对象名.对象名.方法
 */
public static void invokeSetter(Object obj, String propertyName, Object value) {
	Object object = obj;
	String[] names = StringUtil.split(propertyName, StringUtil.DOT);
	for (int i = 0; i < names.length; i++) {
		if (i < names.length - 1) {
			object = ReflectUtil.invoke(object, GETTER_PREFIX + StringUtil.upperFirst(names[i]),
				value);
		} else {
			ReflectUtil.invoke(object, SETTER_PREFIX + StringUtil.upperFirst(names[i]),
				value);
		}
	}
}
 
Example #28
Source File: TaskHandler.java    From openAGV with Apache License 2.0 5 votes vote down vote up
/***
 * 执行任务处理
 * @param target 方法名
 * @param request 请求对象
 * @param response 返回对象
 * @throws Exception
 */
public IResponse doHandler(String target, IRequest request, IResponse response) throws Exception {
    String deviceId = request.getProtocol().getDeviceId();
    try {
        Route route = RouteHelper.duang().getRoutes().get(deviceId);
        if (null == route) {
            return emptyRouteOrMehtod(deviceId, target, request, (BaseResponse) response);
        }
        Method method = route.getMethodMap().get(target.toLowerCase());
        // 如果Service里没有实现该指令对应的方法,则执行公用的duang方法,直接返回响应协议,防止抛出异常
        if (ToolsKit.isEmpty(method)) {
            return emptyRouteOrMehtod(deviceId, target, request, (BaseResponse) response);
        }
        Object resultObj = ReflectUtil.invoke(route.getServiceObj(), method, request, response);
        // 如果是同一个请求响应单元并且rawContent值为空,则写入响应对象
        if (response.isResponseTo(request) &&
                ToolsKit.isEmpty(response.getRawContent())  &&
                ToolsKit.isNotEmpty(resultObj)) {
            response.write(resultObj);
        }
        // 如果响应对象不为空,但没有设置响应内容,则抛出异常
        if (ToolsKit.isNotEmpty(resultObj) && ToolsKit.isEmpty(response.getRawContent())) {
            throw new RobotException(ExceptionEnums.RESPONSE_RAW_NULL);
        }
    } catch (Exception e) {
        if (e instanceof InvocationTargetException) {
            InvocationTargetException ite = (InvocationTargetException) e;
            Throwable t = ite.getTargetException();// 获取目标异常
            throw new RobotException(t.getMessage(), t);
        } else {
            throw new RobotException(e.getMessage(), e);
        }
    }
    return response;
}
 
Example #29
Source File: PageUtil.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 校验分页参数,为NULL,设置分页参数默认值
 *
 * @param condition 查询参数
 * @param clazz     类
 * @param <T>       {@link PageCondition}
 */
public static <T extends PageCondition> void checkPageCondition(T condition, Class<T> clazz) {
    if (ObjectUtil.isNull(condition)) {
        condition = ReflectUtil.newInstance(clazz);
    }
    // 校验分页参数
    if (ObjectUtil.isNull(condition.getCurrentPage())) {
        condition.setCurrentPage(Consts.DEFAULT_CURRENT_PAGE);
    }
    if (ObjectUtil.isNull(condition.getPageSize())) {
        condition.setPageSize(Consts.DEFAULT_PAGE_SIZE);
    }
}
 
Example #30
Source File: QueryWrapperUtil.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static <T> QueryWrapper<T> getWrapper(Object query) {
	QueryWrapper<T> entityWrapper = Wrappers.query();
	if (query == null) {
		return entityWrapper;
	}
	Field[] fields = ReflectUtil.getFields(query.getClass());
	try {
		for (Field field : fields) {
			boolean accessible = field.isAccessible();
			field.setAccessible(true);
			Query q = field.getAnnotation(Query.class);
			if (q != null) {
				String propName = q.propName();
				String blurry = q.blurry();
				String attributeName = StringUtil.isEmpty(propName) ? StringUtil.toRevertCamelCase(field.getName(), CharUtil.UNDERLINE) : propName;
				Object val = field.get(query);
				if (cn.hutool.core.util.ObjectUtil.isNull(val) || "".equals(val)) {
					continue;
				}
				// 模糊多字段
				if (cn.hutool.core.util.ObjectUtil.isNotEmpty(blurry)) {
					String[] blurrys = blurry.split(",");
					entityWrapper.and(i -> {
						for (String s : blurrys) {
							i.or().like(s, val.toString());
						}
					});
					continue;
				}
				parseWarpper(entityWrapper, q, attributeName, val);
			}
			field.setAccessible(accessible);
		}
	} catch (Exception e) {
		log.error(e.getMessage(), e);
	}
	return entityWrapper;
}