Java, NetBeans, and Templates, OH MY!

Written by Troy Howard

09 May 2007

Well, having recently sparked an interest in moving towards a Open Source, cross platform, but still as cool as C#/VS2005 development platform, I of course landed in the middle of NetBeans 5.5 and Java.

Having never programmed in Java before, but understanding it's really similar to C# (or I should say C# is really similar to Java), I immediately started fiddling about as if I were writing C# code. So, it's easy to get past typing uppercase String, not lowercase, and also not too hard to grok extends instead of : for inheritance. The one-class-per-file thing, well, I guess it will just make me a more organized programmer, however annoying it is. Actually, I ended up just learning to do the same thing in C#, which has really been better…

But, the things that really erked me was properties.

In C# I can do this:

// ...

private string _name; 

public string Name
{
    get
    {
        return this._name; 
    }
    set
    {
        this._name = value; 
    }
}

// ... 

but in Java, that looks like:

// ...

private String _name; 

public String getName() {
    return this._name; 
}

public void setName(string value) {
    this._name = value; 
}

// ... 

Wow. Extremely obnoxious. Furthermore, I have finally gotten myself broken in with the VS2005 IDE to type "prop" + TAB to get a nice template for my properties. Well, since there is no such thing in Java, this macro also does not exist. So, I proceeded to make a NetBeans code template called prop, which functions the same way the VS2005 prop code snippet does.

So, for all you C# coders who are venturing into the foreign lands of Java, here's a little tutorial on how to add this little cultural comfort into NetBeans.

Property Code Template Installation Instructions:

  1. Select menu item Tools->Options.

  2. Click on Editor sidebar button.

  3. Click on Code Templates tab.

  4. Select Java from languages combo-box.

  5. Click New, and then enter prop as the Abbreviation in the dialog.

  6. Click Ok.

  7. Make sure prop is the selected template, and in the text box below the list, enter these lines:

    private ${int} ${_prop}; 
    
    public ${int} get${Property}() {
       return this.${_prop}; 
    }
    
    public void set${Property}(${int} value) {
       this.${_prop} = value; 
    }
  8. Select Tab from Expand On combo box.

  9. Click OK.

Now you've got it installed… Feel free to go to the code and give it a whirl! Have a look at the other macros in the list to see what's built in, and once you figure out the syntax of the template notation, make your own templates!