Domanda

In Netbeans you can do stuff like writing "psvm" then pressing tab and it generates

 public static void main(String[] args) {
     //your cursor is placed here.
 }

Similarly there is way to write for cycles, try catch blocks, instanceof checks and stuff like that. Is there anything resembling this approach, to generate a null-check of a variable?

I would like something like this:

ResultSet rs;
rs //pressing some magic button like ctrl+space or "rs null<TAB>" 
   //and a code like this would be generated:

if (rs != null) //your cursor will be placed here.

or

if (rs != null)
{
    //your cursor here
}
È stato utile?

Soluzione

You can create your own template for that:

Go to tools->options->Editor->Code templates->New->Abbreviation: ifnn

Expanded text:

if (${EXP instanceof=”Object”} != null) {
    ${selection}${cursor}
}

Then press "ifnn"+TAB in the editor.

Altri suggerimenti

So I decided to create this template: (A modified version of the accepted answer.)

if(${EXP instanceof="Object"} != null) {
    ${EXP}.${cursor}
} 

assigned to just "nn" standing for "not null".

And also this to validate attributes/parameters at the beginning of methods.

Validate.notNull(${var}, "${var} can't be null");

which I extend by writing "valp" and pressing tab (abbreviation for validate parameter). It is shorter and more concise than:

if(someVar == null){
    throw new Exception("someVar can't be null");
}

which is useful, when there are many validated parameters.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top