Java メモ - Eclipseを使ってJavaのコードスタイルを変更する

プログラムを書くときコードスタイルは個人の好みが反映されて癖があるものだけど、自分が慣れているスタイルだと生産性も高くなる。

例えば多くのJavaプログラマーはこんな感じのスタイルを使っている。

class test(){
    public
main(args[]){
        if(
a == b){
           
System.out.println("Hello World!");
        }
    }
}

個人的には「{ 」を同じ行に書くのは好きになれない。僕はいつも「{ 」が次の行にくるように書いている。こんな感じ。

class test()
{
    public
main(args[])
    {
        if(
a == b)
        {
           
System.out.println("Hello World!");
        }
    }
}

Eclipseはコードを書くときに自動的に括弧などを補ってくれる機能があるけれども、Formatterを使うことで自分のスタイルに合わせることが出来る。

Preferencesを選択して Java --> Code Style --> Formatter で自分のスタイルを設定できる。

既にあるファイルをまとめて変換

既に存在するファイルのコードスタイルをまとめて変換する方法はこちら。

http://wiyoo.blogspot.com/2007/05/batch-formatting-java-source-code-with...

簡単にまとめると。

1. EclipseでJavaのプロジェクトのPropertiesを開く。
2. In Code Style --> Formatterと開いたところで Enable project specific settingsをチェックする。
3. 自分のフォーマットを設定する(既にあればそれを選択)。
4. OKを押す。
5. この状態でEclipseのワークスペースにPreferenceファイルが作成されている。Workspace/プロジェクト名/.settings/org.eclipse.jdt.core.prefs

このファイルを使ってEclipseをコマンドラインで実行。

eclipse -application org.eclipse.jdt.core.JavaCodeFormatter -config D:/formatter.prefs D:/tmp/src

これでD:/temp/src以下にあるすべての .java ファイルが変換される。インターネットからサンプルを拾ってきたりしたときに便利。

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <code> <cite> <ul> <ol> <li> <dl> <dt> <dd> <p>
  • Lines and paragraphs break automatically.
  • Link to Amazon products with: [amazon product_id inline|full|thumbnail]. Example: [amazon 1590597559 thumbnail]
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.