`
Billy_Ao
  • 浏览: 12570 次
  • 性别: Icon_minigender_1
最近访客 更多访客>>
社区版块
存档分类
最新评论

java code Format工具Jalopy介绍

    博客分类:
  • Java
阅读更多
在产品开发中,需要用到使用模板来生成.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>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics