有时候须要处理工具属性的getter、setter方法,或者将属性与数据表字段进行相互转换,这时候就须要用到将小写驼峰转换为小写下划线办法,当然我们可以自己手撸一段代码来实现,但Google的大神们,已经给我们供应了一个现成的开拓包,也便是Google guava包。直接拿来主义吧!
这个非常大略,只须要在工程的pom.xml中引入依赖的坐标即可。
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>25.1-jre</version> </dependency>复制代码
可以做什么
变量的一些转换处理,只须要用到博大精湛的guava包中的一个列举类CaseFormat.class。可以看到该列举类有5个列举变量。

列举便是一个单例,我们可以直策应用列举变量的方法,由于已经是一个单例工具了嘛!
如果你还不理解单例,那这里大略阐明一下,单例便是在一个java进程(也便是当前工程的JVM中)只存在唯一一个工具,列举听说是最大略的单例实现办法了。
那这几个列举常量分别代表什么意思呢?
实在代码的注释里已经阐明的很清楚了,不愧为大神之作啊!
以CaseFormat.LOWER_HYPHEN为例,注释如下:
/ Hyphenated variable naming convention, e.g., "lower-hyphen". /复制代码
代表连字符的变量命名规范,例如user-name,user-age等。
为了减少大家的阅读源码的事情量,这里把5个列举及意义都拿出来说一下。
列举变量
解释
CaseFormat.LOWER_HYPHEN
连字符的变量命名规范,形式lower-hyphen
CaseFormat.LOWER_UNDERSCORE
C++变量命名规范,形式lower_underscore
CaseFormat.LOWER_CAMEL
Java变量命名规范,形式lowerCamel
CaseFormat.UPPER_CAMEL
Java和C++类名命名规范,形式UpperCamel
CaseFormat.UPPER_UNDERSCORE
Java和C++常量命名规范,形式UPPER_UNDERSCORE
一共有5个列举变量,通过排列组合知识,可以知道,我们可以进行变量转换的形式统共有54=20种。
怎么做变量转换下面通过几个范例的例子,演示怎么将一种变量命名规范转换为另一种。
package com.chan.test;import com.google.common.base.CaseFormat;public class GuavaTest { public static void main(String[] args) { // 变量小写连接线转小写驼峰 System.out.println(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, "user-name"));//userName // 变量小写连接线转小写下划线 System.out.println(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_UNDERSCORE, "user-name"));//user_name // 变量小写下划线转小写驼峰 System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "user_name"));//userName // 变量下划线转大写驼峰 System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "user_name"));//UserName // 变量小写驼峰转大写驼峰 System.out.println(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, "userName"));//UserName // 变量小写驼峰转小写下划线 System.out.println(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "userName"));//user_name // 变量小写驼峰转小写下划线 System.out.println(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "UserName"));//user_name // 变量小写驼峰转小写连接线 System.out.println(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, "userName"));//user-name }}复制代码
能够读到末了,解释你很棒哦,来个双击三连吧,奥利给!
作者:chanllenge链接:https://juejin.cn/post/6979188051545178148来源:掘金。