Java工具类的学习

Java工具类的学习

1.StringUtils.isBlank()方法

可判断目标String类型是否为null,“”(空字符串),“ ”。
如:target = null
StringUtils.isBlank()等于true
target = “”
StringUtils.isBlank()等于true
target = " "
StringUtils.isBlank()等于true

2.pageHelper.startPage(currentPage,pageSize)分页查询

currentPage为当前页,以第一页开始
pageSize为每页展示的数量数。

  若要分页查询效果,必须在执行查询SQL语句之前,执行该语句。

3.Maps.newHashMapWithExpectedSize()方法

创建map集合,当可以指定容量
如:map studentMap = Maps.newHashMapWithExpectedSize(3)
创建一个容量为3的map集合,但是当容量不够时,也会自己扩容,无需担心容量问题,其默认容量为16.属于com.google.common.collect.Maps包

4.Json类

5.BeanUtils.copyProperties()方法

org.springframework.beans.BeanUtils.copyProperties(Object sourse,Object target),作用就是把两个对象中相同字段进行赋值。不一定是相同对象,只要两个对象中有相同的成员变量就可以赋值。

6.日志打印类的生成。设置日志的线程信息

 private static final Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class);

org.slf4j.logger和org.slf4j.loggerFactory包

设置线程信息
log4j.appender.console.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss SSS}]%t[%-3p]%c{1}:%X{MDCString}%m%n

7.LinkedHashSet的去重功能

8.MapUtils.getString()方法

org.apache.commons.collectionUtils包下,可以通过key值,直接取得键值。

Map<String,String> map = new HashMap<>();
map.put("name","张三");
String result = MapUtils.getString(map,"name");//得到的结果就是张三

9.CollectionUtils.isEmpty()方法

org.apache.commons.collectionUtils包下,可判断长度为0的list和null的list

10.StringUtils.isEmpty和StringUtils.isBlank方法

org.apache.commons.lang.stringUtils包下,其中isBlank方法可以判断出空字符串的情况

11.MapUtils.isEmpty方法

org.apache.commons.collections.MapUtils包下,可判断长度为0的map和null的map集合。

12.jedisCluster类

redis.clients.jedis包下关于分布式锁的使用

13.从request中取得文件类型进行上传处理

在这里插入图片描述

14.String,format设置保留几位小数

String.format("%.nf",d);
其中n是几,就保留几位小数。如String.format("%.2f",d),则结果保留两位小数
 

15.Calendar.add方法对日期进行操作

时间戳表示格式

String datePattern = "yyyyMMddHHmmssSSS"

如果是1则代表的是对年份操作,2是对月份操作,3是对星期操作,5是对日期操作,11是对小时操作,12是对分钟操作,13是对秒操作,14是对毫秒操作。例如:Calendar calendar = Calendar.getInstance(); calendar .add(5,1);则表示对日期进行加一天操作

16.Maps.newHashMap()创建Map集合符合阿里巴巴规范

创建map集合,属于com.google.common.collect.Maps

17.使用IOUtils关流

IOUtils.closeQuietly(bufferedWriter);

属于org.apache.commons.io包下
注意:java7下,使用下列进行关闭即可

try(BufferedWriter bw = new BufferedWriter ()){
}catch{
}

18.String.split()方法完成对字符串的切割

19.Arrays.asList()方法。将数组转成集合

属于java.util.Arrays包下

    String[] s = {"110","120","130"};
    List<String> array = Arrays.asList(s);//底层还是数组,不能使用集合的方法
    List<String> list = new ArrayList<>(Arrays.asList(s));//这才真正转成了list集合
    System.out.println(list.size());

20.json的使用,属于com.alibaba.fastjson.json

使用前,导入依赖

	<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.28</version>
		</dependency>
1)json.toJsonString()方法

将object类型转成json字符串的类型

 Map map = new HashMap();
        map.put("name","zhangsan");
        map.put("age","13");
        String s = JSON.toJSONString(map);
        System.out.println(s);

得到结果为:{“name”:“zhangsan”,“age”:“13”}

2)JSON.parseObject()方法

将json格式的字符串转成map对象

//json格式的字符串
String s = "{\"isSuccess\":\"T\",\"name\":\"zhangsan\",\"age\":\"17\"}";
        Map resultMap = JSON.parseObject(s);
        System.out.println("得到的map"+resultMap);
        

21.String类型中,换行符

String hh = "\r\n"

22.Documenthelper方法,生成xml文件和解析xml文件

23.审计日志

logger.audit

24.DecimalFormat类,用于格式化十进制数字

DecimalFormat 类主要靠 # 和 0 两种占位符号来指定数字长度。0 表示如果位数不足则以 0 填充,# 表示只要有可能就把数字拉上这个位置。
使用说明

25.Properties类,用于读取Java的配置文件

该类主要用于读取Java的配置文件,不同的编程语言有自己所支持的配置文件,配置文件中很多变量是经常改变的,为了方便用户的配置,能让用户够脱离程序本身去修改相关的变量设置。就像在Java中,其配置文件常为.properties文件,是以键值对的形式进行参数配置的。
读取文件代码参考
第二种读取配置文件
this.getClass().getClassLoader().getResourceAsStream()
自定义一个Properties类,构造器中确定其读取的编码方式

public class LocalProperties extends Properties {

    private String language;

    public LocalProperties (String language){
        this.language = language;
    }
}
public LocalProperties readProperties(String configName){
        //文件类,创建其构造方法设置读取文件的编码方式
        LocalProperties properties = new LocalProperties("UTF-8");
        //获得需读取文件的流
        try (InputStream is = this.getClass().getClassLoader().getResourceAsStream(configName)){
            properties.load(is);
        } catch (IOException e) {
            throw new RuntimeException(e+"读取文件失败");
        }
        return properties;
    }

26.线程安全的map类,ConcurrentHashMap

推荐使用此方法进行map遍历,快捷键为map.entrySet.for

ConcurrentHashMap map = new ConcurrentHashMap();
        for (Object o : map.entrySet()) {
            System.out.println("推荐此方法进行map遍历");
        }

25.Collections.sort()方法实现自定义排序

自定义的对象实现Comparable接口,重写compareTo方法

 List<ComparableStudy> list = new ArrayList<>();
        ComparableStudy study = new ComparableStudy();
        list.add(study);
        Collections.sort(list);
        System.out.println("排序后得到的List"+list);

26.ApplicationContext类

org.springframework.context.ApplicationContext

@Autowired
private ApplicationContext context;

Spring上下文,可从Sring容器中拿到服务类

27.ThreadPoolExecutor类

java.util.concurrent.ThreadPoolExecutor

private TreadPoolExecutor executor;

@PostConstruct
private void init(){
	// 设置线程池大小
	executor = new ThreadPoolExecutor(20, 20, 5, 
	TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(20), new ThreadFactory(){
@Override
public Thread new Thread(Runnable r){
	Thread t = new Thread(r);
	t.setName("线程");
	return t;
}
},new ThreadPoolExecutor.DiscardPolicy());
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
@Override
public void run(){
executor.shutdown();
}
}));
)
}

参数解析
int corePoolSize 指定了线程池中的线程数量,它的数量决定了添加的任务是开辟新的线程去执行,还是放到workQueue任务队列中取
int maximumPoolSize 指定了线程池中的最大线程数量,这个参数会根据你使用的workQueue任务队列的类型,决定线程池会开辟的最大线程数
long keepAliveTime 当线程池中空闲线程数量超过corePoolSize时,多余的线程会在多场时间内被销毁
TimeUnit unit keepAliveTime的单位
BlockingQueue workQueue 任务队列,被添加到线程池中,但尚未被执行的任务;它一般分为直接提交队列、有界任务队列、无界任务队列、优化任务队列几种
ThreadFactory threadFactory 线程工厂,用于创建线程,一般用默认即可
RejectedExecutionHandler handler 拒绝策略;当任务太多来不及处理时。如何拒绝任务

28.断言的使用

常用的断言封装在org,junit,jupiter.api.Assertions类中,均为静态方法
Assertions类

常用的断言方法

29.RandomUtils随机数工具类使用

对应包org.apache.commons.lang3.RandomUtils

long l = RandomUtils.nextLLong(0,999L);

30.继承HttpServletRequestWrapper,重写getParamterValues方法,对请求参数进行过滤

链接: 包装HttpServletRequestWrapper.

31.继承OncePerRequestFilter编写自己的过滤器

链接: OncePerRequestFilter的简述.

@Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
	//可增加开关
	boolean isSwitchOpen = isSwitchOpen();
	if (isSwitchOpen ) {
		XssHttpServletRequestWrapper xssRequest = new XssHttpServletRquestWrapper(request);
		chain.doFilter(xssRequest,response);
	}	

}

32.AOP切入同类的调用方法

AopContext

SecReportDataInfoServiceImpl service = (SecReportDataInfoServiceImpl) (AopContext.currentProxy)

33.DecimalFormat类(java.text包)

 DecimalFormat df = new DecimalFormat("0000");
 String format = df.format(12);
 System.out.println("结果是:"+format);
        //结果是 0012

DecimalFormat的占位符说明

34.MessageFormat类(java.text包)

String str = MessageFormat.format(“my name is :{0},age is :{1},height is:{2}”, “zhangsan”, 18, 180);

在这里插入图片描述

35.Deque接口类的介绍

队列函数。deque.peek()查看栈顶元素

 public static boolean isValid(String s) {
        if(s == null || s.length() <= 0){
            return false;
        }

        if(s.length() % 2 != 0){
            return false;
        }

        char[] chars = s.toCharArray();
        int length = chars.length;


        Deque<Character> paramList = new LinkedList<>();
        for(int i = 0;i< length;i++){
            char c = s.charAt(i);
            if(c == '('){
            	//入栈
                paramList.push(')');
            } else if(c == '{'){
                paramList.push('}');
            } else if(c=='['){
                paramList.push(']');
            } else if(paramList.isEmpty() || paramList.peek() != c){
                return false;
            } else {
            	//出栈
                paramList.pop();
            }

        }

        if(paramList.isEmpty()){
            return true;
        }

        return false;

    }

36.实现InitializingBean和ApplicationContextAware接口完成对类的初始化操作

package com.ruoyi.framework.config.properties;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import org.apache.commons.lang3.RegExUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import com.ruoyi.common.annotation.Anonymous;

/**
 * 设置Anonymous注解允许匿名访问的url
 * 
 * @author ruoyi
 */
@Configuration
public class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware
{
    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

    private ApplicationContext applicationContext;

    private List<String> urls = new ArrayList<>();

    public String ASTERISK = "*";

    @Override
    public void afterPropertiesSet()
    {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        map.keySet().forEach(info -> {
            HandlerMethod handlerMethod = map.get(info);

            // 获取方法上边的注解 替代path variable 为 *
            Anonymous method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Anonymous.class);
            Optional.ofNullable(method).ifPresent(anonymous -> Objects.requireNonNull(info.getPatternsCondition().getPatterns())
                    .forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK))));

            // 获取类上边的注解, 替代path variable 为 *
            Anonymous controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Anonymous.class);
            Optional.ofNullable(controller).ifPresent(anonymous -> Objects.requireNonNull(info.getPatternsCondition().getPatterns())
                    .forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK))));
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException
    {
        this.applicationContext = context;
    }

    public List<String> getUrls()
    {
        return urls;
    }

    public void setUrls(List<String> urls)
    {
        this.urls = urls;
    }
}

37.StopWatch类对接口耗时进行统计

StopWatch stopWatch = new StopWatch();
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值