前言
在实际项目开发中,会碰到这样的问题,数据库表结构设计好了,可实体类还没相应地弄出来。实体类的属性命名方法一般是驼峰法,而数据库中的表字段命名方法用的是下划线法。如果表的字段非常多,我们根据设计好的数据库字段再手动敲写一遍驼峰法的属性,这有点费时了。如何迅速地把数据库中的表字段变成我们所需要的驼峰式的属性呢?
解决方法有二,一是通过文本编辑工具,如EditPlus,Notepad++等,利用它们携带的正则替换功能来迅速实现;二是通过自己编写工具类来实现。至于第一种方法操作技巧,不在这边赘述。
第二种方法如下:
以下是自己编写的工具类的代码:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
package day0704;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 驼峰法-下划线互转
* @author cshaper
* @since 2015.07.04
* @version 1.0.0
*/
public class Underline2Camel {
/**
* 下划线转驼峰法
* @param line 源字符串
* @param smallCamel 大小驼峰,是否为小驼峰
* @return 转换后的字符串
*/
public static String underline2Camel(String line, boolean smallCamel){
if (line== null || "" .equals(line)){
return "" ;
}
StringBuffer sb= new StringBuffer();
Pattern pattern=Pattern.compile( "([A-Za-z\\\\d]+)(_)?" );
Matcher matcher=pattern.matcher(line);
while (matcher.find()){
String word=matcher.group();
sb.append(smallCamel&&matcher.start()== 0 ?Character.toLowerCase(word.charAt( 0 )):Character.toUpperCase(word.charAt( 0 )));
int index=word.lastIndexOf( '_' );
if (index> 0 ){
sb.append(word.substring( 1 , index).toLowerCase());
} else {
sb.append(word.substring( 1 ).toLowerCase());
}
}
return sb.toString();
}
/**
* 驼峰法转下划线
* @param line 源字符串
* @return 转换后的字符串
*/
public static String camel2Underline(String line){
if (line== null || "" .equals(line)){
return "" ;
}
line=String.valueOf(line.charAt( 0 )).toUpperCase().concat(line.substring( 1 ));
StringBuffer sb= new StringBuffer();
Pattern pattern=Pattern.compile( "[A-Z]([a-z\\\\d]+)?" );
Matcher matcher=pattern.matcher(line);
while (matcher.find()){
String word=matcher.group();
sb.append(word.toUpperCase());
sb.append(matcher.end()==line.length()? "" : "_" );
}
return sb.toString();
}
public static void main(String[] args) {
String line= "I_HAVE_AN_IPANG3_PIG" ;
String camel=underline2Camel(line, true );
System.out.println(camel);
System.out.println(camel2Underline(camel));
}
}
|
运行结果如下:
iHaveAnIpang3Pig
I_HAVE_AN_IPANG3_PIG
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用Java能有一定的帮助,如果有疑问大家可以留言交流。
原文链接:http://www.cnblogs.com/javasharp/p/4622413.html
相关文章
猜你喜欢
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 49
-
2025-05-25 31
-
详解Spring Cloud Stream使用延迟消息实现定时任务(RabbitMQ)
2025-05-29 43 -
使用自助建站微信小程序时,怎样选择合适的模板以匹配品牌形象?
2025-06-04 78 -
2025-05-29 88
热门评论