かずきのBlog

C#やJavaやRubyとメモ書き

目次

Blog 利用状況

ニュース

わんくまBlogが不安定になったため、前に書いてたはてなダイアリーにメインを移動します。
かずきのBlog@Hatena
技術的なネタは、こちらにも、はてなへのリンクという形で掲載しますが、雑多ネタははてなダイアリーだけに掲載することが多いと思います。
コメント
プログラマ的自己紹介
お気に入りのツール/IDE
プロフィール
経歴
広告
アクセサリ

書庫

日記カテゴリ

[NetBeans][Java]Alt + Insertで出るコードジェネレーションをカスタマイズ

NetBeans6系で気に入ってる機能の1つ!Alt + Insertでコードを色々生成出来るってのがある。
エディタ上でAlt + Insert(若干押しにくい)を押すと下のようなものが出てくる
image

ここから生成したいコードを選ぶと、さくっとコードが出力される。
例えば、equals() and hashCode()...を選ぶと
image

どのフィールドを対象にするかを選択するダイアログが出てきて
image

こんな感じのコードが出力される

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Employees other = (Employees) obj;
        if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
            return false;
        }
        if (this.name != other.name && (this.name == null || !this.name.equals(other.name))) {
            return false;
        }
        if (this.entDate != other.entDate && (this.entDate == null || !this.entDate.equals(other.entDate))) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 19 * hash + (this.id != null ? this.id.hashCode() : 0);
        hash = 19 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 19 * hash + (this.entDate != null ? this.entDate.hashCode() : 0);
        return hash;
    }

これをカスタマイズしてみようと思う。

 

プロジェクト作成

まず、モジュールのプロジェクトを作成する。名前は何でもいいけど、とりあえずinsertという名前にした。
パッケージはcom.wankuma.kazuki.insertにしておいた。layer.xmlを使うので生成するようにしておく。

そして、ライブラリに以下の3つを追加する。Java Editorのほうは、公式に公開されてるものじゃないみたいなので、Non-API Modulesからみつけるようにする。

  1. Javac API Wrapper
  2. Java Editor(Show Non-API Modulesにチェックを入れないと出てこない)
  3. Java Source

そして、ここでもう一手間。
これから使うクラスは、まだ公開されてないということなので、無理やり使うように設定する。
Java Editorで右クリックしてEdit...を選択する。

出てきたダイアログで、Specification VersionからImplementation Versionに変更する。
image

 

Let's プログラミング!

そしたらおもむろにクラスを作成する。名前はcom.wankuma.kazuki.insert.HelloCodeGeneratorにする。
そしてorg.netbeans.modules.java.editor.codegen.CodeGeneratorをimplementsする。

package com.wankuma.kazuki.insert;

import javax.swing.text.JTextComponent;
import org.netbeans.modules.java.editor.codegen.CodeGenerator;

public class HelloCodeGenerator implements CodeGenerator {

    public String getDisplayName() {
        return null;
    }

    public void invoke(JTextComponent textComponent) {
    }

}

getDisplayNameはAlt + Insertのときに表示されるテキスト。invokeは、実際の挿入処理を行うみたい。
さくっと実装してみた。

    public String getDisplayName() {
        return "Hello world";
    }

    public void invoke(JTextComponent textComponent) {
        // キャレットの位置を取得して
        int mark = textComponent.getCaret().getMark();
        try {
            // そこに適当な文字列を挿入する
            textComponent.getDocument().insertString(
                    mark, "System.out.println(\"Hello world\");", null);
        } catch (BadLocationException ex) {
            Logger.getLogger(HelloCodeGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

そして、Generatorを生成するためのファクトリクラスを作成する。
とりあえずHelloCodeGeneratorの内部クラスにする。

public class HelloCodeGenerator implements CodeGenerator {

    // ファクトリクラス!
    public static class Factory implements CodeGenerator.Factory {
        // Iterableを返すらしいので、さくっとね
        public Iterable<? extends CodeGenerator> create(CompilationController arg0, TreePath arg1) throws IOException {
            return Collections.singleton(new HelloCodeGenerator());
        }
        
    }
    
    public String getDisplayName() {
    // 以下略

}

後は、ファクトリクラスを、layer.xmlのEditors/text/x-java/codegeneratorsに登録する。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.1//EN" "http://www.netbeans.org/dtds/filesystem-1_1.dtd">
<filesystem>
    <folder name="Editors">
        <folder name="text">
            <folder name="x-java">
                <folder name="codegenerators">
                    <file name="com-wankuma-kazuki-insert-HelloCodeGenerator$Factory.instance" />
                </folder>
            </folder>
        </folder>
    </folder>
</filesystem>

これで完成!!

 

実行してみよう

F6を押して実行!テスト用NetBeansが立ち上がる。

適当にJavaのプロジェクトを作成してJavaのコードエディタ内でAlt + Insertをしてみると....
image

出た!!選択すると…
image

お~出た~。
こんな手軽にいけるなら、がんがん俺様フレームワークのスニペットみたいなのを作れるんじゃないだろうか。
単純に固定区を入れるものから、設定ファイルからコード生成するものとか…

夢は広がる。

投稿日時 : 2008年5月14日 23:13

Feedback

# [NetBeans][Java]コードジェネレータを作ってみよう(NB5.5) 2008/09/13 22:00 かずきのBlog

[NetBeans][Java]コードジェネレータを作ってみよう(NB5.5)

# welded ball valve 2012/10/18 23:00 http://www.jonloovalve.com/Full-welded-ball-valve-

I like this web blog so much, saved to my bookmarks. "Nostalgia isn't what it used to be." by Peter De Vries.

# エルメスクリスマス 2012/12/14 23:13 http://www.hermespairs.info/category/エルメスバーキン

You truly know an individual's stuff...

# longchamp bag outlet 2012/12/15 16:18 http://www.longchampbagoutlet.info/category/longch

I am sure I will probably visit that place once again soon.

# burberry solde 2012/12/16 5:10 http://www.sacburberryecharpe.fr/category/burberry

The fashion don't retract flat and Philips doesn't supply a travel pouch inside package.

# sacslongchamp2012 2012/12/16 22:30 http://www.sacslongchamp2012.info

It's OK. You can be a dailymotion star =)

# Michael Kors Bracelet 2012/12/17 8:41 http://www.sacmichaelkors.net/michael-kors-bracele

Those are way more awesome. Looks including klipsch is essentially made to employ iProducts? I have android variants!

# burberry sale 2012/12/17 19:18 http://www.burberryoutlet2012.info/category/burber

While performing my racing games and paying attention to fast songs:D

# burberrycanadaoutlet.info 2012/12/17 21:46 http://www.burberrycanadaoutlet.info

Keep in the excellent succeed.

# sacs pliage longchamp 2012/12/18 6:26 http://sacspliagelongchamps.webnode.fr

This can be described as really fine site publish, im delighted I recently came across it.

# bags burberry outlet 2012/12/18 21:32 http://www.burberryoutlet2012.info/category/burber

Keep up the excellent function.

# michael kors pas cher 2012/12/18 22:50 http://sac-michael-kors.webnode.fr/blog/

Thus, our shelves land up filled with items that we experience.

# burberry bags 2012/12/19 14:10 http://burberryoutlet2013sale.webeden.co.uk

Keep in the excellent succeed.

# sac michael kors 2012/12/21 8:29 http://sac-michael-kors.webnode.fr/blog/

These glimpse great.

# kicksonfire 2013/03/05 0:42 http://www.jordanretro10air.com/

To the world may well a single person, however to at least one someone may well life. kicksonfire http://www.jordanretro10air.com/

# lunettes 3d 2013/03/05 0:43 http://www.g33.fr/

To everyone you're likely to be one person, but nevertheless , to at least one woman / man you're likely to be our society. lunettes 3d http://www.g33.fr/

# jordan 13 2013/03/05 0:43 http://www.nike44.com/

I adore explore due to whom you are, but nonetheless , due to exactly who I am certain individuals morning on hand. jordan 13 http://www.nike44.com/

# jordanretro3air.com 2013/03/05 0:45 http://www.jordanretro3air.com/

Even though anybody doesn‘capital t adore you how we want them in,doesn‘capital t ensure the companies don‘capital t adore you with they have. jordanretro3air.com http://www.jordanretro3air.com/

# Jordan Retro 4 2013/03/05 0:46 http://www.jordanretro4air.com/

Not any man or woman is really worth your main cry, as well as individual who is undoubtedly gained‘testosterone levels allow you to scream. Jordan Retro 4 http://www.jordanretro4air.com/

# Jordan Retro 11 2013/03/05 0:46 http://www.nikerow.com/

Glee really is a scent you can't pour out for a number of people not including remember , getting a handful droplets for that you are. Jordan Retro 11 http://www.nikerow.com/

# la redoute soldes 2013/03/05 0:47 http://www.k88.fr/

True love often is the involved interest on your life-style also , the growth of what our organization really enjoy. la redoute soldes http://www.k88.fr/

# casquette supreme 2013/03/15 5:15 http://www.b44.fr/

When you really need any shipping in the worth, count number your buddies. casquette supreme http://www.b44.fr/

# destockchine 2013/03/24 0:40 http://c99.fr/

One particular honestly most likely not someone i know, and yet someone i know are invariably a good solid honestly. destockchine http://c99.fr/

# usine23 2013/03/24 0:41 http://e55.fr/

To everyone you should be anyone, yet , to one person you should be the whole world. usine23 http://e55.fr/

# destockchine 2013/03/24 0:41 http://d77.fr/

In the will make your magic formula starting from an enemy, determine this task never a colleague. destockchine http://d77.fr/

# casquette chicago bulls 2013/04/03 22:22 http://www.laredoutecode.fr/

Really enjoy, solidarity, reverence, be careful not to combine folk over a typical hate with regards to a thing. casquette chicago bulls http://www.laredoutecode.fr/

# 3suisses 2013/04/07 1:20 http://ruenee.com/

To everyone you might be one person, but nevertheless , to one person you might be the globe. 3suisses http://ruenee.com/

# Laredoute 2013/04/07 5:11 http://ruezee.com/

A brother most likely not a mate, yet somehow a mate will almost always be a suitable brother. Laredoute http://ruezee.com/

タイトル
名前
Url
コメント