Java Code Examples for cn.hutool.core.util.ReflectUtil

The following examples show how to use cn.hutool.core.util.ReflectUtil. These examples are extracted from open source projects. 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 Project: openAGV   Source File: IocHelper.java    License: 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 2
Source Project: openAGV   Source File: RouteHelper.java    License: 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 3
Source Project: openAGV   Source File: RouteHelper.java    License: 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 4
Source Project: openAGV   Source File: ActionRequest.java    License: 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 5
Source Project: yue-library   Source File: BeanPropertyRowMapper.java    License: 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 6
Source Project: zuihou-admin-boot   Source File: NoBootTest.java    License: 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 7
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 8
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 9
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 10
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 Project: spring-boot-demo   Source File: MessageController.java    License: 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 12
Source Project: scaffold-cloud   Source File: I18nTransformUtil.java    License: 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 13
Source Project: bitchat   Source File: HtmlMakerFactory.java    License: 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 14
Source Project: zuihou-admin-cloud   Source File: NoBootTest.java    License: 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 Project: spring-boot-demo   Source File: BaseDao.java    License: 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 16
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 17
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 Project: spring-boot-demo   Source File: BaseDao.java    License: 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 19
Source Project: spring-boot-demo   Source File: MessageController.java    License: 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 20
Source Project: redant   Source File: HtmlMakerFactory.java    License: 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 21
Source Project: albedo   Source File: ExcelUtil.java    License: 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 22
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 23
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 24
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 25
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 26
Source Project: spring-boot-demo   Source File: MessageController.java    License: 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 27
/**
 * 获取自定义的 request
 *
 * @param clazz  枚举类 {@link AuthSource}
 * @param source {@link AuthSource}
 * @return {@link AuthRequest}
 */
@SuppressWarnings("unchecked")
private AuthRequest getExtendRequest(Class clazz, String source) {
    try {
        EnumUtil.fromString(clazz, source.toUpperCase());
    } catch (IllegalArgumentException e) {
        // 无自定义匹配
        return null;
    }

    Map<String, ExtendProperties.ExtendRequestConfig> extendConfig = properties.getExtend().getConfig();

    // key 转大写
    Map<String, ExtendProperties.ExtendRequestConfig> upperConfig = new HashMap<>(6);
    extendConfig.forEach((k, v) -> upperConfig.put(k.toUpperCase(), v));

    ExtendProperties.ExtendRequestConfig extendRequestConfig = upperConfig.get(source.toUpperCase());
    if (extendRequestConfig != null) {
        Class<? extends AuthRequest> requestClass = extendRequestConfig.getRequestClass();

        if (requestClass != null) {
            // 反射获取 Request 对象,所以必须实现 2 个参数的构造方法
            return ReflectUtil.newInstance(requestClass, (AuthConfig) extendRequestConfig, authStateCache);
        }
    }

    return null;
}
 
Example 28
Source Project: openAGV   Source File: TaskHandler.java    License: 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 Project: mall-learning   Source File: HutoolController.java    License: Apache License 2.0 5 votes vote down vote up
@ApiOperation("ReflectUtil使用:Java反射工具类")
@GetMapping("/reflectUtil")
public CommonResult reflectUtil() {
    //获取某个类的所有方法
    Method[] methods = ReflectUtil.getMethods(PmsBrand.class);
    //获取某个类的指定方法
    Method method = ReflectUtil.getMethod(PmsBrand.class, "getId");
    //使用反射来创建对象
    PmsBrand pmsBrand = ReflectUtil.newInstance(PmsBrand.class);
    //反射执行对象的方法
    ReflectUtil.invoke(pmsBrand, "setId", 1);
    return CommonResult.success(null, "操作成功");
}
 
Example 30
Source Project: spring-boot-demo   Source File: PageUtil.java    License: 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);
    }
}