java 常用的一些工具方法 有更新!

Published on with 299 views

/**

     * 获取指定值
     * @param name 属性名
     * @return
     */
    public <T> T  get(String name) {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (name.equals(field.getName())) {
                String firstLetter = name.substring(0, 1).toUpperCase();
                String getter = "get" + firstLetter + name.substring(1);
                try {
                    Method method = this.getClass().getMethod(getter);
                    return (T) method.invoke(this);
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }
        return null;
    }
    /**
     * 给指定值赋值
     * @param name 属性名
     * @return
     */
    public void set(String name,String value) {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (name.equals(field.getName())) {
                String firstLetter = name.substring(0, 1).toUpperCase();
                String setter = "set" + firstLetter + name.substring(1);
                try {
                    Method method = this.getClass().getMethod(setter, String.class);
                    method.invoke(this, value);
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
/**
 * 自定义
 * @param map
 * @return
 */
public Criteria andEqualTo(Map<String,Object> map) {
    for (String key: map.keySet()) {
        Object value = map.get(key);
        String condition = StringUtils.humpToLine(key);//实体属性转化成数据库字段(转下划线_)
        addCriterion(condition + " = ", value, key);
    }
    return (Criteria) this;
}

/**
 * 自定义
 * @return
 */
public Criteria andIsNotNull(String filedName) {
    String condition = StringUtils.humpToLine(filedName);//实体属性转化成数据库字段(转下划线_)
    addCriterion(condition + " is not null");
    return (Criteria) this;
}

Responses