Java常用的一些方法和工具类
1.定义数组三种方式
int[] arr =new int[10]; int[] arr = new int[]{2,3,4,5,5}; int[] arr = {2,4,5,6,6};
2.Arrays.toString(数组) //将数组中的数据转为字符串
3."liuliu.big".substring(''liuliu.big''.lastIndexOf(".")) //用于得到最后的后缀名 lastIndexof是指最后一个给定的字符串(不包含)往前数的个数 ,substring是截取给定数值(不包含)往后的所有
4.Arrays.asList()//将某些数据转换为集合
5.byte[] bytes = "liuliu".getBytes(); //将字符串转为byte数组
6.arg(0).toString()
toString()方法底层是new String的形式,新建一个对象,调用userId.toString().intern();这时候当调用toString()方法时先去常量池中寻找有没有这个值,有就直接拿取。
7.list.foreach(lambda函数) //遍历集合
8.arg(0).getClass().equals(String.class) //判断是否为字符串
9.UUID.randomUUID().toString() //生成uuid,toString(true),true代表生成下划线,(hutool工具中)
UUID类没有true这个参数需要通过replace方法替换比如
String uuidString = UUID.randomUUID().toString();
uuidString.replace(“-”,“”);
10.BeanUtils.copyProperties(item, dishDto); //将item这个对象拷贝给dishDto,一般在strem流的map中使用,拷贝的对象中不可以有和对象相同的范型类比如拷贝page分页的时候page里有一个record属性应该单独拿出来设置。
hutool工具类中也有这个方法;
11.String s2 = JSON.toJSONString(liuliu); //bean对象转换为Json形式的字符串 fastJson2依赖
User user = JsonObject.parseObject(str,User.class);
12.hutool工具使用(详见https://www.hutool.cn/)
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.3</version>
</dependency>
//StrUtil字符串类
//判断是否为空字符串
isnotempty和isnotblank的区别是内部有没有空格,isnotempty如果有空格的话会显示true也就是不为空,isnotblank有空格的时候会返回false代表有空格也算空.
String str = "test";
StrUtil.isBlank(str);
StrUtil.isEmpty(str);
StrUtil.isNotEmpty(str);
//将集合用逗号隔开转换成一个字符串
StrUtil.join(“,”,集合);
//去除字符串的前后缀
StrUtil.removeSuffix("a.jpg", ".jpg");
StrUtil.removePrefix("a.jpg", "a.");
//格式化字符串
String template = "这只是个占位符:{}";
String str2 = StrUtil.format(template, "我是占位符");
LOGGER.info("/strUtil format:{
}", str2);
//随机生成一个数字,后缀根据需求设定,比如String等等
RandomUtil.randomNumbers(6);
//包装类直接判断和拆箱(如果包装类直接拿回来用可能发生空指针问题)
Boolean flag;
BooleanUtil.isTrue(flag);
BooleanUtil.isBoolean();
//将String类型的属性转换为bean对象,常用于redis的存储单个值并且为空的时候使用
//将bean对象转换为Json格式的字符串
String s = JSONUtil.toJsonStr(liuliu);
//将String类型(必须是json格式)转为bean对象,其实也不单单只能转String类型。下面的hutool中的JSONObject类型也可以
Student liuliu = JSONUtil.toBean("{'age':20,'name':'liuliu'}", Student.class);
//将object类型强转为JSONObject
JSONObject str = (JSONObject)redisData.getData();
//BeanUtil可用于Map与JavaBean对象的互相转换以及对象属性的拷贝。
PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("小米");
brand.setShowStatus(0);
//Bean转Map
Map<String, Object> map = BeanUtil.beanToMap(brand);
LOGGER.info("beanUtil bean to map:{}", map);
//将json格式的字符串转化成集合类型(非常适用于嵌套集合)
String jsonString = “[[1,2,‘3’],[5,7,8]]”
List<List<Object>> list = JSON.parseObject(jsonString,new TypeReference<List<List<object>>>(){}) ;
json.parseObjects是fastjson中的,typereference是hutool中的
//Map转Bean
// 2023/2/6 5.将查询到的hush数据转为User对象,false为不忽略转换过程中的错误,第二个参数传的是一个bean对象或者新建对象
PmsBrand mapBrand = BeanUtil.mapToBean(map, PmsBrand.class, false);
LOGGER.info("beanUtil map to bean:{}", mapBrand);
//第二种
// 2023/2/6 5.将查询到的hush数据转为User对象,false为不忽略转换过程中的错误,第二个参数传的是一个bean对象或者新建对象
User cashUser = BeanUtil.fillBeanWithMap(entriesUser, new User(), false);
//Bean属性拷贝
PmsBrand copyBrand = new PmsBrand();
BeanUtil.copyProperties(brand, copyBrand);
LOGGER.info("beanUtil copy properties:{}", copyBrand);
bean转map plus版
Map<String, Object> usertoMap = BeanUtil.beanToMap(phoneUser,new HashMap<>(),
CopyOptions.create()
.setIgnoreNullValue(true)
.setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString())
);
13.commons-lang3包
StringUtils.isEmpty //这个方法判断的是字符串是否为null或者其长度是否为零。
StringUtils.isBlank // 这个方法除了判断字符串是否为null和长度是否为零,还判断了是否为空格,如果是空格也返回true。
14.LocalDateTime time=LocalDateTime.now() //获取当前时间,LocalDateTime是日期格式2023-04-15T01:08:39.298
LocalDateTime.now().plusSeconds(30L) //将当前时间往后移30秒
localDateTime.isAfter(time); //判断是否在某个时间之后是否过期
locaDateTime.of(2022,2,2,2,2,2); //得到Localtime的时间
long currentTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC); //得到当前时间转化的秒数
//格式化日期为yyyy:MM:dd时间
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy:MM:dd");
String date = LocalDateTime.now().format(dateTimeFormatter);
如果修饰类型是Localdatetime的话那么可以用以上localdatetime时间
如果是timestamp修饰的话那么要用new TimeStamp()来转,参数类型为long
15.解决空指针异常提前处理(不用后来用到报异常错误)直接限制它的参数不为空
(1) Assert.notNull(Student,"User is null");
(2) 直接在需要的方法或者参数上添加@nullable注解