JAVA工具类
一、概述
1. 字符串占位符
// 字符串占位 // 方法一:使用String的静态方法format String format = String.format(" %s * %s = %s", "2", "3", 5); // 2 * 3 = 5 System.out.println("format: " + format); // 方法二:功能强大,支持指定类型和格式,性能更好,但是需要指定参数位置 // 参考:https://blog.csdn.net/GarfieldEr007/article/details/89397843 String format1 = MessageFormat.format(" {0} * {1} = {2}", "2", "3", 5); // 2 * 3 = 5 System.out.println("format1: " + format1); // 方法三:日志输出中使用占位符 try { int a = 2 / 0; } catch (Exception e) { log.info(" {} * {} = {}", "2", "3", 5, e); } // 方法四: 没有换行符 // 2 * 3 = 5 System.out.printf(" %s * %s = %s", "2", "3", 5); System.out.println();
2、StopWatch
2.1 lang3
StopWath是 apache commons lang3 包下的一个任务执行时间监视器,与我们平时常用的秒表的行为比较类似。
依赖:
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.6</version> </dependency>
API:
示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static void main(String[] args) throws InterruptedException { //创建后立即start,常用 StopWatch watch = StopWatch.createStarted(); // StopWatch watch = new StopWatch(); // watch.start(); Thread.sleep(1000); System.out.println(watch.getTime()); System.out.println("统计从开始到现在运行时间:" + watch.getTime() + "ms"); Thread.sleep(1000); watch.split(); System.out.println("从start到此刻为止的时间:" + watch.getTime()); System.out.println("从开始到第一个切入点运行时间:" + watch.getSplitTime()); Thread.sleep(1000); watch.split(); System.out.println("从开始到第二个切入点运行时间:" + watch.getSplitTime()); // 复位后, 重新计时 watch.reset(); watch.start(); Thread.sleep(1000); System.out.println("重新开始后到当前运行时间是:" + watch.getTime()); // 暂停 与 恢复 watch.suspend(); System.out.println("暂停2秒钟"); Thread.sleep(2000); // 上面suspend,这里要想重新统计,需要恢复一下 watch.resume(); System.out.println("恢复后执行的时间是:" + watch.getTime()); Thread.sleep(1000); watch.stop(); System.out.println("花费的时间》》" + watch.getTime() + "ms"); // 直接转成s System.out.println("花费的时间》》" + watch.getTime(TimeUnit.SECONDS) + "s"); }
参考:https://mp.weixin.qq.com/s/SRL94kccWCPTe_NlLj0bRg