java code Format工具Jalopy介绍

在产品开发中,需要用到使用模板来生成.java文件,这就需要使用Jalopy等Format工具来实现代码的格式设置,Jalopy就是一种强大的Java code Format工具,下面简单介绍一下他的是用:


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;

import de.hunsicker.jalopy.Jalopy;

public class FormatJava {
static URL convention = null;
static Jalopy jalopy = null;
private static void init()throws FormatException{
try {
convention = FormatJava.class.getResource("/META-INF/convention.xml");
Jalopy.setConvention(convention);
jalopy = new Jalopy();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new FormatException(e.getMessage());
}

}

public static void format(File file)throws FormatException{
if(jalopy == null)
init();
try {
String name = file.getName();
if(name.endsWith(".java")){
jalopy.setInput(file);
jalopy.setOutput(file);
jalopy.format();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
new FormatException(e.getMessage());
}
}

public static void format(String fileName)throws FormatException{
if(jalopy == null)
init();
if(fileName == null)
return;
if(!fileName.endsWith(".java"))
return;
File file = new File(fileName);
if(!file.exists())
return;

try {
jalopy.setInput(file);
jalopy.setOutput(file);
jalopy.format();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
new FormatException(e.getMessage());
}
}


}

这里的convertion.xml中定义了关于java文件中的相关格式,里边的子项主要是包括方法参数是否现实,是否缩进等,下面是一个基本的例子:
[color=blue]
<?xml version="1.0" encoding="UTF-8"?>
<jalopy>
<internal>
<version>6</version>
</internal>
<printer>
<alignment>
<parameterMethodDeclaration>true</parameterMethodDeclaration>
</alignment>
<blanklines>
<after>
<header>2</header>
<lastImport>1</lastImport>
<method>1</method>
</after>
</blanklines>
<braces>
<insert>
<dowhile>true</dowhile>
<for>true</for>
<ifelse>true</ifelse>
<while>true</while>
</insert>
</braces>
<imports>
<grouping>
<defaultDepth>1</defaultDepth>
<packages>java:1|javax:1|org:1|gnu:1|*:0</packages>
</grouping>
<policy>disabled</policy>
<sort>true</sort>
</imports>
<indentation>
<policy>
<deep>true</deep>
</policy>
<sizes>
<extends>8</extends>
<implements>8</implements>
</sizes>
</indentation>
<wrapping>
<always>
<before>
<extends>true</extends>
<implements>true</implements>
</before>
</always>
<general>
<enable>true</enable>
</general>
</wrapping>
</printer>
</jalopy>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值